JavaScript单击事件触发两次 [英] Javascript click event triggers twice

查看:765
本文介绍了JavaScript单击事件触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码段中,为什么单击<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规范在

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

For example, on platforms where clicking a checkbox label checks the checkbox, clicking the label in the following snippet could trigger the user agent to run synthetic click activation steps on the input element, as if the element itself had been triggered by the user:

<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单击事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆