如何防止儿童点击父母点击

时间:2011-12-13 05:43:04

标签: jquery click

我已完成以下代码结构,并点击addClass item_box_popup执行removeClass item_boxitem_box div

<div class="item_box"> <!--This is the small div which when clicked changes to the item_box_popup div-->
  <div class="name">...</div>
  <div class="detail">...</div>
</div>

<div class="item_box_popup"> <!--This div expands to show the detail and the children in it has a click event-->
  <div class="name">...</div>
  <div class="detail">...</div>
</div>

item_box div中有一个点击事件,而不是孩子。工作是在点击时将div更改为item_box_pop div addClassremoveClass

item_box_popup没有点击事件,但子项已定义了点击事件。我们使用delegate来定义.item_box_popup .name等的点击事件。

问题是,当我们点击item_box div时,.item_box_popup .name定义的点击事件也会被触发。这可能是因为点击.item_box时定义的更改类。

单击.item_box时,我不希望在子项上触发click事件。我已经尝试undelegate停止触发点击item_box子项,只是执行点击中定义的更改类,但这不起作用。

.item_box

的点击事件
$('.slide > div').bind('click',function(e) {
    if(!$(this).hasClass('item_box_popup')){
        var index=$('.slide > div').index(this);
            $(this).removeClass('item_box');
            $(this).addClass('item_box_popup');     
        Nomad.config.firstVisibleItem=index;<!--This is to set the position for .item_box_popup-->              
    }           
});

.item_box_popup

的点击事件
$("body").delegate('.item_box_popup .name, .item_box_popup .detail','click', function(e){
  //working code here for this
});

e.stopPropagation();停用.item_box

的默认点击处理程序

2 个答案:

答案 0 :(得分:5)

您需要使用stopPropagation阻止事件“冒泡”到父级:http://api.jquery.com/event.stopPropagation/

答案 1 :(得分:1)

尝试添加event.preventDefault();在您确实想要发生的通话之后,它会停止发生默认操作,例如一个元素的默认动作。

我不能确切地说出在哪里尝试这个电话,或者它是否会在没有看到你的js代码的情况下解决你的问题。 html不是你的问题所在,它是js代码,所以如果这个(或者我在输入这个时发布的其他答案!)不起作用,你可以编辑你的帖子来包含你的js吗?

<强>更新

我已将您的代码复制到JSFiddle并添加了对item_box点击处理程序的e.stopPropagation()调用,它按预期工作:http://jsfiddle.net/chkaQ/2/

当你点击item_box子div时,它会将其更改为item_box_popup并且不会执行item_box_popup子点击事件...我错了,还是不是你想要它做什么?