踩坑 点击事件出现两次,事件委托

1、HTML

<div class="name"  onclick="aaa()">
            <input  type="radio" name="hobby" id="www"><label for="www">虎儿歌</label>
    </div>
    <div class="name"  onclick="aaa()">
            <input type="radio" name="hobby" id="www"><label for="www">虎儿歌</label>
    </div>

2、js

  function aaa(){
      console.log(111)
  }

3、效果

 可以看到点击后方法执行两次 ,

测试办法,检查事件对象的源触发

4、HTML

<div  class="name"  >
            <input type="radio" name="hobby" id="www"><label for="www">虎儿歌</label>
    </div>
    <div class="name">
            <input  type="radio" name="hobby" id="xxx"><label for="xxx">虎儿歌</label>
    </div>

5、js 

var c = document.getElementsByClassName('name');

    for(var i = 0;i<c.length;i++){
        c[i].addEventListener('click',function(e){
            console.log(e)
            console.log(22222)
        },false)
    }

6.结果  

 可以看到两次的事件源对象不一样,

第一次是label第二次是input,点击input本身不会执行两次,

可以确定当label的for属性绑定了input的id,,点击label会相当于点击input,即input会变为选中状态

 当吧事件绑定在input时,点击label也会触发input的点击事件,‘

结论:label  绑定了input后点击label相当于点击input,所以在父元素同时有label和input并且绑定时,就会出现两次

解决:利用事件委托,判断源触发对象当为 label时,不执行,或者改变其嵌套关系;

猜你喜欢

转载自www.cnblogs.com/guyuedashu/p/12045373.html