点击事件触发两次 [英] Click event triggering two times
问题描述
我点击标签文字时尝试运行某些函数,但点击事件触发了两次。
HTML_HTML
< label class =label_one>
Label One
< input type =checkbox/>
< / label>
但是如果我像这样更改html代码就不会发生。
< label for =testclass =label_two>
Label Two
< input type =checkbox/>
< / label>
我的脚本是这样:
$('。label_one')click(function(){
console.log('testing');
});
任何人都可以向我解释为什么会发生这样的情况。
My jsfiddle是这里检查它。
https://jsfiddle.net/sureshpattu/ hvv6ucu8 / 3 /
这是因为事件冒泡。
一般来说,所有元素都会将事件文档,而标签
标签会将事件冒泡到其子节点,以及当您单击标签dom时如何输入标签。
因此,在您的情况下,您将事件处理程序附加到label标签,因此
<
要解决这个问题,只需将事件处理程序附加到输入/ checkbox标签应该可以正常工作。
I am trying to run some function when clicking on the label text but the click event fired two times.
HTML
<label class="label_one">
Label One
<input type="checkbox"/>
</label>
But its not happening if I change the html code like this.
<label for="test" class="label_two">
Label Two
<input type="checkbox"/>
</label>
My script is this:
$('.label_one').click(function(){
console.log('testing');
});
Can anyone explain me why this is happening like this.
My jsfiddle is here check it ones.
https://jsfiddle.net/sureshpattu/hvv6ucu8/3/
It is because of event bubbling.
In general all elements bubble the event to the root of the document whereas the label
tag will bubble the event to its child nodes and thats how the input tag is getting ticked when you click the label dom.
So in your case you attached the event handler to label tag so
- It calls when label tag gets clicked
- event bubbles inside it and checkbox gets selected and checkbox bubbles the event to its parent node that is
label
tag again hence it is called twice.
To solve this, just attach the event handler to input/checkbox tag it should work fine.
这篇关于点击事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!