首页 > 解决方案 > 我想通过单击按钮停止传播...在此代码中,我可以通过复选框执行操作,但我想通过单击按钮执行相同的操作

问题描述

<!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..?

标签: javascript

解决方案


这可以使用点击计数器来完成。像这样:

let btn_click = false;

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

btn_click此外,在 if 条件中使用变量的值:

...
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>


推荐阅读