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
227 views
in Technique[技术] by (71.8m points)

javascript - Isolate click listener in overlapping row and button

I have a table as below: one column shows text, the other column contains buttons. I need to implement two different actions: one when the row itself is clicked, one when the button is clicked.

But in the code below, I cannot isolate the two events when I click the buttons: meaning, both actions are executed since the row is also considered as "clicked". How do I isolate the two events? I have to use appendChild as the button is created dynamically in my actual code. Thanks.

var r1cell2 = document.getElementById('r1cell2');
var r1c2Button = document.createElement("button")
r1c2Button.innerHTML = "R1C2"
r1cell2.appendChild(r1c2Button)

let r1 = document.getElementById("r1")
r1.addEventListener("click", () => {
  alert("R1 clicked")
})

r1c2Button.addEventListener("click", () => {
  alert("R1C2 Button clicked")
})
<table id="tableId">
  <tr id="r1">
    <td id="r1cell1">Cell R1C1</td>
    <td id="r1cell2"></td>
  </tr>
  <tr id="r2">
    <td id="r2cell1">Cell R2C1</td>
    <td id="r2cell2"></td>
  </tr>
</table>
question from:https://stackoverflow.com/questions/65886806/isolate-click-listener-in-overlapping-row-and-button

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

1 Reply

0 votes
by (71.8m points)

You can use event.stopPropagation() to contain event handling at button-level.

var r1cell2 = document.getElementById('r1cell2');
var r1c2Button = document.createElement("button")
r1c2Button.innerHTML = "R1C2"
r1cell2.appendChild(r1c2Button)

let r1 = document.getElementById("r1")
r1.addEventListener("click", () => {
  console.log("R1 clicked")
})

r1c2Button.addEventListener("click", (e) => {

  e.stopPropagation();
  // ^^^^^ Here you can stop event being passed to upper level event listener
  
  console.log("R1C2 Button clicked")
})
<table id="tableId">
  <tr id="r1">
    <td id="r1cell1">Cell R1C1</td>
    <td id="r1cell2"></td>
  </tr>
  <tr id="r2">
    <td id="r2cell1">Cell R2C1</td>
    <td id="r2cell2"></td>
  </tr>
</table>

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

...