开发者

jQuery click events overriding each other

开发者 https://www.devze.com 2023-04-10 01:25 出处:网络
I have the following jQuery: $(\'.io-sidebar-section\').click(function () { console.log(\'Section C开发者_如何学Golicked\');

I have the following jQuery:

$('.io-sidebar-section').click(function () {
      console.log('Section C开发者_如何学Golicked');
      $(this).next().fadeToggle('fast',function(){});
    });

    $('.io-sidebar-section-advanced-toggle').click(function(){
      $(this).parent().next().children('.io-sidebar-link-advanced').fadeToggle('fast',function(){});
    });

the advanced toggle is inside of a sidebar section. When I click on the advanced toggle, it executes the sidebar section click.

How can I seperate these two out?


You can use the stopPropagation method of the event object inside the click event handler for the child element:

$('.io-sidebar-section-advanced-toggle').click(function(e){
    e.stopPropagation();
    $(this).parent().next().children('.io-sidebar-link-advanced').fadeToggle('fast',function(){});
});

From the jQuery docs, here's what stopPropagation does:

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

As mentioned in the comments, if you prefer you can alternatively use return false in the event handler (in this particular case, as far as I can tell anyway - it will also cause preventDefault which may not be what you want to happen). My personal preference is to use stopPropagation but it's completely up to you.


You can avoid events bubbling up by using jQuery's bind function and preventBubble argument.

http://api.jquery.com/bind/

0

精彩评论

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