单击子项会触发父项

时间:2015-07-14 15:35:00

标签: jquery

我在这方面发现了很多问题,但没有一个解决方案对我有好处。当我有多个元素堆叠在一起时,我一直在体验一个功能(在我的情况下出现问题)。我有这样的dom情况。

<div class="body" data-type="body" onclick="foo(this)">
  <div class="container" data-type="container" onclick="foo(this)">
  </div>
</div>

所以当我点击.body console.log显示正确的元素。当我点击.container时,两个元素都会触发onclick事件。有没有办法克服这个问题?或者是否有可能添加听众?我的纯jquery方法看起来像这样。当然,当我使用纯jquery时,我没有内联onclick。

function initSelectable(){
  $('*[data-type]:not(.item-wrapper)').unbind('click').bind('click',function(){
    console.log($(this));
  });
}

感谢您的每一个建议和/或答案!

1 个答案:

答案 0 :(得分:1)

确保事件没有传播。使用此:

event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();

在您的代码中:

function initSelectable(){
  $('*[data-type]:not(.item-wrapper)').unbind('click').bind('click',function(event) {
    console.log($(this));
    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();
  });
}