单击儿童onclick时,忽略父级onclick,仅使用Javascript [英] Ignore parent onclick when child onclick is clicked, using Javascript only
问题描述
这就是我想要实现的目标与此:
< div class =overlay_display_production_list_backgroundid =overlay_display_production_list_background_idonclick =this.style.display ='无>
< table class =table_production_availabilityid =table_production_availability_idonclick =this.parentElement.style.display ='block'>
< / table>
< / div>
然而这不起作用。我如何得到这个工作,我只想纯java脚本。
谢谢 解决方案
避免内在事件属性(如的onclick
)。使用JavaScript绑定您的事件处理程序。利用事件对象来防止事件在DOM上进一步传播(所以它永远不会到达父级,因此不会触发绑定到它的事件处理程序)。
document.querySelector(div)。addEventListener(click,parent); document.querySelector(div div)。 addEventListener(click,child); function parent(event){console.log(Parent clicked);} function child(event){event.stopPropagation(); console.log(Child clicked);}
div {padding:2em;背景:red;} div div {background:blue;}
< DIV> < DIV> < / div>< / div>
An good example of what im trying to do is, think of instragram. When you are click on a photo, it opens a window with that photo plus the grey background. If you click anywhere in the grey background the picture is closed, however if you click on the picture the picture remains in the window.
This is what I am trying to achieve with this:
<div class="overlay_display_production_list_background" id="overlay_display_production_list_background_id" onclick="this.style.display = 'none'">
<table class="table_production_availability" id="table_production_availability_id" onclick="this.parentElement.style.display = 'block'">
</table>
</div>
However this doesnt work. how do I get this working, I only want Purely java-script.
Thanks
Avoid intrinsic event attributes (like onclick
). Bind your event handlers with JavaScript. Take advantage of the event object to prevent further propagation of the event up the DOM (so it never reaches the parent and thus doesn't trigger the event handler bound to it).
document.querySelector("div").addEventListener("click", parent);
document.querySelector("div div").addEventListener("click", child);
function parent(event) {
console.log("Parent clicked");
}
function child(event) {
event.stopPropagation();
console.log("Child clicked");
}
div {
padding: 2em;
background: red;
}
div div {
background: blue;
}
<div>
<div>
</div>
</div>
这篇关于单击儿童onclick时,忽略父级onclick,仅使用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!