如何防止儿童点击父母点击
我已经完成了以下代码结构,并在单击item_box div
执行addClass item_box_popup
和removeClass item_box
item_box div
。
... ... ... ...
item_box div
中包含click事件而不是子项。 工作是在单击时通过addClass
和item_box_pop div
更改为item_box_pop div
。
item_box_popup
没有单击事件,但子项已定义click事件。 我们使用delegate
来定义.item_box_popup .name
等的click事件。
问题是当我们单击item_box div
,为.item_box_popup .name
定义的click事件也会被触发。 这可能是由于针对.item_box
点击定义的更改类.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; } });
.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
的默认单击处理程序
尝试添加event.preventDefault(); 在您确实想要发生的调用之后,它会停止发生默认操作,例如元素的默认操作。
我不知道确切地在哪里尝试这个电话,或者它是否会在没有看到你的js代码的情况下解决你的问题。 html不是你的问题所在,它是js代码,所以如果这个(或者我输入这个时发布的其他答案!)不起作用你能编辑你的post来包含你的js吗?
更新:
我已经将你的代码复制到JSFiddle并添加了一个e.stopPropagation()调用item_box单击处理程序,它按预期工作: http : //jsfiddle.net/chkaQ/2/
当您单击item_box子div时,它会将其更改为item_box_popup并且不会执行item_box_popup子点击事件…我是否弄错了,或者这不是您想要它做的?
您需要使用stopPropagation阻止事件“冒泡”到父级: http : //api.jquery.com/event.stopPropagation/