开发者

Not clear on this jQuery syntax: return !$()

I saw this code and 开发者_如何转开发I'm not clear what the '!' does in this line of jQuery code on the return on the jQuery object:

$('#remove').click(function() {
    return !$('#select2 option:selected').appendTo('#select1');
});

EDIT

What is a good case to do this?


It converts the result of $('#select2 option:selected').appendTo('#select1') to a boolean, and negates it.

However, as the result of appendTo is always a jQuery object, and an object (jQuery or not) is always truthy, the result of !$('#select2 option:selected').appendTo('#select1') is always false.

So what we have is effectively:

$('#remove').click(function() {
    $('#select2 option:selected').appendTo('#select1');

    return false;
});

Returning false in a jQuery event handler will stop the default event action occuring (e.g. the submission of a form/ navigation of a hyperlink) and stop the event propagating any further up the DOM tree.

So what we have is effectively:

$('#remove').click(function(e) {
    $('#select2 option:selected').appendTo('#select1');

    e.preventDefault();
    e.stopPropagation();
});

Using return false instead of e.preventDefault(); e.stopPropagation(); is OK, but using the return !$(..) as a shortcut for the first example is ridiculous, and there is no need to do it.

Just to reiterate my point, the most important thing to note here is that there is never, ever a good reason/ case to do this.

Links:

  1. Docs for bind() (alias for click())
  2. Docs for preventDefault()
  3. Docs for stopPropagation()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜