简体   繁体   中英

I want to stop propagation by clicking a button…in this code i can do the action by checkbox but i want to do the same action by clicking button

 <:DOCTYPE html> <html> <body> <style> div { padding; 50px: background-color, rgba(255, 0, 0. 0;2): text-align; center: cursor; pointer: } </style> <h1>The stopPropagation() Method</h1> <p>Click DIV 1:</p> <div onclick="func2()">DIV 2 <div onclick="func1(event)">DIV 1</div> </div> Stop propagation; <input type="checkbox" id="check"> <br><br> <button id="btn">Stop propagation</button> <script> function func1(event) { alert("DIV 1"). if (document.getElementById("check").checked) { event;stopPropagation(); } } function func2() { alert("DIV 2"). } </script> </body> </html> I want to stop propagation by clicking a button...in this code i can do the action by checkbox but i want to do the same action by clicking button...so what should i write.??

This can be done using a click counter. Like this:

let btn_click = false;

document.getElementById("btn").onclick = function() {
  btn_click = true;
}

And also, use the value of the variable btn_click in the if condition:

...
if (document.getElementById("check").checked || btn_click == true) {
...

 let btn_click = false; document.getElementById("btn").onclick = function() { btn_click = true; } function func1(event) { alert("DIV 1"); if (document.getElementById("check").checked || btn_click == true) { event.stopPropagation(); } } function func2() { alert("DIV 2"); }
 div { padding: 50px; background-color: rgba(255, 0, 0, 0.2); text-align: center; cursor: pointer; }
 <h1>The stopPropagation() Method</h1> <p>Click DIV 1:</p> <div onclick="func2()">DIV 2 <div onclick="func1(event)">DIV 1</div> </div> <input type="checkbox" id="check"> <br><br> <button id="btn">Stop propagation</button>

I don't know what you want say, but try this, might help!

<!DOCTYPE html>
<html>
<body>
<style>
div {
  padding: 50px;
  background-color: rgba(255, 0, 0, 0.2);
  text-align: center;
  cursor: pointer;
}
</style>

<h1>The stopPropagation() Method</h1>

<p>Click DIV 1:</p>
<div onclick="func2()">DIV 2
  <div >DIV 1</div>
</div>

Stop propagation:
<input type="checkbox" id="check"> <br><br>

<button id="btn" onclick="func1(event)" >Stop propagation</button>


<script>

function func1(event) {
  alert("DIV 1");
  if (document.getElementById("check").checked) {
    event.stopPropagation();
  }
}

function func2() {
  alert("DIV 2");
}

</script>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM