单击儿童onclick时,忽略父级onclick,仅使用Javascript [英] Ignore parent onclick when child onclick is clicked, using Javascript only

查看:98
本文介绍了单击儿童onclick时,忽略父级onclick,仅使用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个很好的例子,我想要做的是,想想instragram。当你点击一张照片时,它会打开一张带有该照片加上灰色背景的窗口。如果您点击灰色背景中的任何地方,图片会关闭,但是如果您点击图片,图片仍会保留在窗口中。



这就是我想要实现的目标与此:

 < 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆