点击事件触发两次 [英] Click event triggering two times

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

问题描述



我点击标签文字时尝试运行某些函数,但点击事件触发了两次。

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

    1. It calls when label tag gets clicked
    2. 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屋!

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