问题
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?
JSFiddle
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>
回答1:
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
来源:https://stackoverflow.com/questions/40368276/window-click-event-is-getting-called-twice