下面是我的html。
// consider all are of same size
<div id="grand-parent">
<div id="parent">
<div id = "child">
</div>
</div>
</div>Javascript。
$("#grand-parent").click(function(){
alert("grand-parent");
});
$("#parent").click(function(){
alert("grand-parent");
});
// consider this as child event but actual child event comes from third party.
$("#parent").click(function(){
return false;
});这些事件按子、父、祖父母的顺序绑定。现在,当我单击div时,子元素事件将首先触发,返回false。这将阻止事件冒泡。但我希望家长的点击率事件也需要触发。
拦截器:子单击事件总是先绑定,它是第三方api,所以我们不能触摸。
任何帮助都是值得感激的。
发布于 2017-01-31 10:11:56
您可以使用下面的代码,如果您单击子,那么第一个祖父母将触发,然后是子,然后是父。如果单击“父”,则“父级”事件将触发,而如果单击“父级”,则只会触发“父级”。在这段代码中,我应用了事件捕获的概念,所以大父级将首先调用,然后控制转到子级,然后是父级。
JS小提琴链接-
https://jsfiddle.net/oe1qxsub/
HTML -
<div id="grand-parent">
<div id="parent">
<div id = "child">
</div>
</div>
</div>JS -
$("#grand-parent").get(0).addEventListener("click", function(){
alert("grand-parent");
}, true);
$("#parent").click(function(){
alert("parent");
});
$("#child").click(function(){
alert('child');
});CSS -
#grand-parent{
background:blue;
width:80px;
height:80px;
}
#parent{
background:red;
width:50px;
height:30px;
}
#child{
background:yellow;
width:20px;
height:20px;
}发布于 2017-01-31 10:36:24
https://stackoverflow.com/questions/41954379
复制相似问题