How can I get jQuery to ignore parents on .click()
Sample code:
<div id="a">
<div id="b">
Click here
</div>
</div>
<script>
$('*').click(function() {
alert($(this).attr('id'));
});
</script>
When you click 'Click Here' it alerts twice, once with 'b' and then with 'a'.
开发者_StackOverflow社区I need to figure out how to get jQuery to ignore all the parents of where the user clicked and just alert, in this case, 'b'.
Try this:
$('*').click(function(e) {
e.stopPropagation();
// do something
});
Here you can find documentation: http://api.jquery.com/event.stopPropagation/
Try using $('body').delegate('*', 'click', fn)
instead of direct event handlers. (See jQuery.delegate.) It will be called exactly once for each event, and you can find out from the event object which element was affected.
You are using the "All Selector" http://api.jquery.com/all-selector/
I think you are looking for this:
$('#b').click(function() {
alert( $(this).attr('id') );
});
Use stopPropagation:
$('*').click(function(event) {
alert($(this).attr('id'));
event.stopPropagation();
});
精彩评论