"Select all, excluding" selector in JQuery
I have a DIV that contains many child elements like e.g. other DIVs, SPANs and links.
Is it possible to specify in JQuery selector that I want to call a function开发者_运维知识库 whenever an element of this DIV (including the DIV itself) is clicked, with the exception of all links (a
), where this function should not be called?
Instead of selecting all and excluding some elements and bind event handlers to each of them, the easier way (imo) would be to attach the event handler just to the div
and test whether a link was clicked or not (event delegation):
$('#yourDiv').click(function(event) {
if(event.target.nodeName !== 'A') {
// do your stuff
}
});
This would only work if the links don't have any other elements as children.
More robust might be using .delegate
[docs] and the :not
[docs] pseudo selector:
Update: Apparently, you have to add another click
event handler to the div
to be able to detect clicks on the div
itself (my tests with using the delegate selector only failed):
$('#yourDiv')
.delegate(':not(a)', 'click', handler)
.click(function(event) {
if(event.target === this) { // only if the `div` was clicked
handler.apply(this, arguments);
}
});
Here, handler
is the actual event handler you want to execute. By using an extra function, you don't have to repeat the code.
$('div#div_id, div#div_id *:not(a)').click(function(){
// do whatever you like here
});
Demo
You can use the jQuery not()
method to achieve what you are looking for.
e.g.
$('div, div *').not('a').click(function(){
//handle click
});
alternately you could use the :not()
selector
e.g.
$('div, div *:not(a)').click(function(){
//handle click
});
But I personally find the first method more readable and prettier.
You could use the the .not()
method to exclude elements.
精彩评论