Trigger action when element is clicked but not when some specific subelements are
I have a div, containing text a开发者_如何学Cnd a few links. I want to trigger an onclick event, only if the click occurs anywhere in the div, but not on any of the links.
What would be the best way (performance wise) to implement this using jQuery?
The one I use is
$('#div').click(function(){
});
but it disables all the #div > a
You can use the :not() Selector
$("#div :not(a)").click(function(){
});
This will bind click to all elements inside the div which are not <a>
tags.
$("#div").click(function(e){
if (e.target.tagName === "A")
{
return false;
}
else
{
alert("click");
}
});
This will bind a click handler to div itself and then check for the target and if it is not <a>
then alert will be shown.
$('#div').bind('click', function(e){
if(e.target == this){
// do something
}
});
精彩评论