Why is my click event called twice in jquery?

前端 未结 3 918
無奈伤痛
無奈伤痛 2020-12-15 08:09

Why is my click event fired twice in jquery?

HTML

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 08:39

    I recommend you use the change event on the input[type="checkbox"] which will only be triggered once. So as a solution to the above problem you might do the following:

    $("#toggle").on("change", function(e) {
      if ($(this).is(":checked"))
        console.log("toggle: Show");
      else
        console.log("toggle: Hide");
    });
    

    https://jsfiddle.net/ssrboq3w/

    The vanilla JS version using querySelector which isn't compatible with older versions of IE:

    document.querySelector('#toggle').addEventListener('change',function(){
      if(this.checked)
        console.log('toggle: Show');
      else
        console.log('toggle: Hide');
    });
    

    https://jsfiddle.net/rp6vsyh6/

提交回复
热议问题