开发者

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();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜