Why the onclick element will trigger twice for label element

后端 未结 5 1915
时光说笑
时光说笑 2020-11-27 07:18



        
5条回答
  •  佛祖请我去吃肉
    2020-11-27 07:53

    If your intention is to respond only to clicks on the label and not on the checkbox, you can look at the event.target property. It references the element that called the listener so that if the click wasn't on that element, don't to the action:

    window.onload = function(){
      var el = document.getElementById('wow');
      el.addEventListener('click', function(event) {
    
        if (this === event.target) {
          /* click was on label */
          alert('click was on label');
    
        } else {
          /* click was on checkbox */
          event.stopPropagation();
          return false;
        }
    
      }, false);
    }
    

    If, on the other hand, you want to only respond to clicks on the checkbox (where a click on the label also produces a click on the checkbox), then do the reverse. Do nothing for clicks on the label and let ones from the checkbox through:

    window.onload = function(){
      var el = document.getElementById('foolabel');
      el.addEventListener('click', function(event) {
    
        if (this === event.target) {
          /* click was on label */
          event.stopPropagation();
          return false;
    
        } else {
    
          /*
          ** click is from checkbox, initiated by click on label
          ** or checkbox                                  
          */
    
          alert('click from checkbox');
        }
    
      }, false);
    }
    

    This version seems to have the most natural behaviour. However, changing the markup so that the label no longer wraps the checkbox will mean the listener is not called.

提交回复
热议问题