问题描述
在以下代码段中,为什么单击<label>
时divClicked()
触发两次,但是单击<input>
时仅一次?
In the following snippet, why does divClicked()
trigger twice when the <label>
is clicked, but only once when <input>
is clicked?
function divClicked(_index) {
console.log("div click event");
}
function inputClicked(_index) {
console.log("input click event");
}
<div class="option" onclick="divClicked(1)">
<input id="1_1" name="group_1" type="radio" value="1" onclick="inputClicked(1)" />
<label for="1_1">label</label>
</div>
注意::我想知道为什么发生这种情况,而不是像"在标签上放置onclick()"这样的快速修复".
Note: I want to know why this happens, not a "quick fix" like: put onclick() on label.
推荐答案
由于HTML规范在 4.10.4 :
<label><input type=checkbox name=lost> Lost</label>
在其他平台上,该行为可能只是为了集中控制, 还是什么都不做.
On other platforms, the behavior might be just to focus the control, or do nothing.
这意味着单击<label>
时,浏览器将在关联的<input>
元素上创建第二个合成"点击事件,以切换其状态.
This means that when a <label>
is clicked, the browser creates a second "synthetic" click event on the associated <input>
element, in order to toggle its state.
divClicked
触发两次的原因是,第一个事件<label>
冒泡直到<div>
,第二个综合点击事件冒泡到<div>
.
The reason divClicked
is triggered twice, is because the first event which comes from the <label>
bubbles up to the <div>
, and also the second, synthetic click event bubbles up to the <div>
.
这篇关于JavaScript单击事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!