Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...