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:
- Docs for
bind()
(alias forclick()
) - Docs for
preventDefault()
- Docs for
stopPropagation()
精彩评论