Click event in parent and children
我有一个具有子div元素的父元素DIV。对于父级及其子级,我有单独的单击实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $('#mainContainer').click(function () { console.log('main container'); }).children().click(function () { console.log('childen'); return false; }); $('#childContainer2').click(function () { console.log('child container 2'); }); |
这很好。但是如果我单击一个孩子,则该事件将运行两次,这应该是这样的。我的问题是-有没有一种方法可以将事件显式地写入父级,而不会影响子级,从而使子级不需要两次执行单击功能?
是的,您可以更改绑定事件的顺序并停止传播,请使用stopImmediatePropagation
考虑这个小提琴
1 2 3 4 5 6 7 8 9 10 11 12 | $('#childContainer2').click(function (e) { alert('child container 2'); e.stopImmediatePropagation() return false; }); $('#mainContainer').click(function () { alert('main container'); }).children().click(function (e) { alert('childen'); return false; }); |
两者
您可以使用use event.stopPropagation:
1 2 3 4 5 | children().click(function (e) { e.stopPropagation(); console.log('childen'); return false; }); |
防止事件起泡