为什么onclick元素会为标签元素触发两次 [英] Why the onclick element will trigger twice for label element

查看:691
本文介绍了为什么onclick元素会为标签元素触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< pre class =snippet-code-js lang-js prettyprint-override> window.onload = function(){var wow = document.getElementById(wow); wow.onclick = function(){alert(hi); }}

< label id =wow> < input type =checkboxname =checkboxvalue =value> Text< / label>



这是我的代码,当我点击文本时,它会提醒嗨两次,但当我点击框时, onclick 元素只会触发一次,为什么?解析方案

当你点击标签时,它会触发点击处理程序,而你获得警报。



但是点击标签也会自动向相关的输入元素发送一个点击事件,所以这被视为点击复选框。然后事件冒泡导致在包含元素上触发点击事件,这是标签,因此您的处理程序会再次运行。



如果您将HTML更改为此,您不会收到双重提醒:

 < input id =wowcbtype =checkboxname =复选框value =value> 
< label id =wowfor =wowcb>文字< / label>

标签现在与使用的复选框关联属性而不是环绕它。



DEMO


      window.onload = function(){
         var wow = document.getElementById("wow");
    	 wow.onclick = function(){
    	     alert("hi");
    	 }
      }

    <label id="wow"><input type="checkbox" name="checkbox" value="value">Text</label>

This is my code, when I clicked on "Text" it will alert hi twice but when I clicked on the box, the onclick element will only trigger once, why?

解决方案

When you click on the label, it triggers the click handler, and you get an alert.

But clicking on a label also automatically sends a click event to the associated input element, so this is treated as a click on the checkbox. Then event bubbling causes that click event to be triggered on the containing element, which is the label, so your handler is run again.

If you change your HTML to this, you won't get the double alert:

<input id="wowcb" type="checkbox" name="checkbox" value="value">
<label id="wow" for="wowcb">Text</label>

The label is now associated with the checkbox using the for attribute instead of wrapping around it.

DEMO

这篇关于为什么onclick元素会为标签元素触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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