Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
937 views
in Technique[技术] by (71.8m points)

html - Ignore parent onclick when child onclick is clicked, using Javascript only

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...