我想通过单击按钮来停止传播..在这段代码中,我可以通过复选框执行操作,但我希望通过单击按钮执行相同的操作



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

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

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

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

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

我不知道你想说什么,但试试这个,可能会有所帮助!

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

最新更新