jQuery selector with exlude of element & elements children
I have a div used for filtering and i want it to close when anything outside of the div is clicked. The selector I am trying to build, basically selects all elements except a specific element and excludes its children. Here is what I have tried,开发者_JAVA百科 but haven't been able to get working
$('*:not(:has(.exclude *))').live('click', function() {HideFilter();});
page structure is simplified to this:
<div></div>
<div>
<div></div>
<div>
<div class="exclude"><inputs></div>
</div>
<div></div>
</div>
so I want all of the divs, but the one and everything in the .exclude to have the event. I have been at this for a while, I need some help.
Have you tried
$('*:not(.exclude, .exclude *)').live( ... )
? [edit[ Ah I see - the problem is that even if you exclude the stuff, the events still bubble up.
Try something like this:
$('*').live('click', function(e) {
if (!$(e.target).is('.exclude, .exclude *'))
// do interesting stuff
}
return false;
});
That should stop event propagation on the excluded things without actually doing anything.
Example page: http://gutfullofbeer.net/balloon.html
edit update, 3 years later: the .live()
method is at this point long-deprecated. That last example should look like this in new code:
$('body').on('click', '*', function(e) {
if (!$(e.target).closest('.exclude').length) {
// do interesting stuff
}
return false;
});
how about a slightly different strategy:
close everything when anything but the div is clicked:
$("body").click(function(e){
if($(e.target).hasClass("exclude")){
//show stuff
} else {
//hide stuff
}
});
something like that
精彩评论