Javascript点击事件触发两次

Zze*_*Zze 9 html javascript

在下面的代码片段中,为什么在单击时会divClicked()触发两次<label>,但在单击时只触发一次<input>

function divClicked(_index) {
  console.log("div click event");
}

function inputClicked(_index) {
  console.log("input click event");
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

注意:我想知道为什么会发生这种情况,而不是像"快速修复"那样:在标签上放置onclick().

4ca*_*tle 11

这是因为HTML规范在4.10.4中描述的内容:

例如,在单击复选框标签的平台上选中复选框,单击label以下代码段可能会触发用户代理在 元素上运行合成点击激活步骤input,就好像元素本身已由用户触发:

<label><input type=checkbox name=lost> Lost</label>
Run Code Online (Sandbox Code Playgroud)

在其他平台上,行为可能只是集中控件,或什么都不做.

这意味着当<label>单击a时,浏览器会在关联<input>元素上创建第二个"合成"点击事件,以便切换其状态.

原因divClicked是两次触发,是因为第一个事件来自<label>气泡直到<div>第二个合成点击事件起泡到了<div>.

  • darnit!在移动设备上写出一个很长的答案真的很难! (2认同)