javascript - 我想通过单击按钮停止传播...在此代码中,我可以通过复选框执行操作,但我想通过单击按钮执行相同的操作
问题描述
<!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;
}
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>
推荐阅读
- c - C 编程:如何忽略输入?
- reactjs - setState 不更新状态
- python - Python >= 3.3 内部字符串表示
- python - Python 应用程序返回 MySQL 数据 3 次而不是 1 次
- c - C中的阶乘计算
- reactjs - 使用 normlizr 的 Redux :将数据转移到 normlizr 对象
- reactjs - 如何区分打字稿中的地图和字符串值?
- confluent-platform - 如何更改融合的休息代理正文数据模式以生成消息
- python - 如何检查项目是否有特定的类,所以我们不在 selenium 中打印它
- google-cloud-platform - 谷歌云监控 - 获取正常运行时间检查当前状态