window click event is getting called twice [duplicate]

♀尐吖头ヾ 提交于 2020-01-06 15:33:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!