窗口点击事件被调用两次 [英] window click event is getting called twice
问题描述
我在窗口
上有点击事件。复选框还有一个复选框和一个标签。当您点击标签时,窗口的
点击事件将被调用两次,一次为复选框,一次为标签。
我尝试添加 e.stopPropagation();
到事件侦听器,但它没有帮助。为什么该事件被调用两次,我该如何解决呢?
var checkbox = document.getElementById('checkbox-id'); window.addEventListener('click',function(e){console.log(checkbox.checked,e.target)}); console.clear
input {display:none;} label {background-color : 橙子; width:100px; height:100px; display:block;} input:checked label {background-color:green;}
< input type =checkboxname =checkboxid =checkbox-id/>< label for =checkbox-id>< / label>
要停止它,请使用 stopPropagation()
方法:
var checkbox = document.getElementById ');
window.addEventListener('click',function(e){
console.log checked,e.target)
e.stopPropagation();
});
有关事件顺序和冒泡的更多详情: http://www.quirksmode.org/js/events_order.html
I have an click event on window
. There is also a checkbox and a label for the checkbox. When you click on the label, the window's
click event gets called twice, once for the checkbox, and once for the label.
I tried adding e.stopPropagation();
to the events listener, but it didn't help. Why is the event getting called twice, and what can I do to fix it?
var checkbox = document.getElementById('checkbox-id');
window.addEventListener('click', function(e) {
console.log(checkbox.checked, e.target)
});
console.clear();
input {
display: none;
}
label {
background-color: orange;
width: 100px;
height: 100px;
display: block;
}
input:checked label {
background-color: green;
}
<input type="checkbox" name="checkbox" id="checkbox-id" />
<label for="checkbox-id"></label>
The event bubbles up. To stop that, use the stopPropagation()
method:
var checkbox = document.getElementById('checkbox-id');
window.addEventListener('click', function(e) {
console.log(checkbox.checked, e.target)
e.stopPropagation();
});
For more details on event order and bubbling: http://www.quirksmode.org/js/events_order.html
这篇关于窗口点击事件被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!