Home  >  Article  >  Web Front-end  >  The event bound to Jquery on triggers multiple instance codes

The event bound to Jquery on triggers multiple instance codes

高洛峰
高洛峰Original
2017-01-04 14:09:581708browse

Use the 'on' function to bind an event to a new button. This event will be triggered multiple times.

<html> 
<head> 
  <meta name="viewport" content="width=device-width" /> 
  <title>码上飘</title> 
  <script src="/FrontStyle/js/jquery-1.11.2.min.js" type="text/javascript"></script> 
  <script> 
    $(function(){ 
      $(&#39;#btn1&#39;).click(function () { 
        $(&#39;#btnBind&#39;).on(&#39;click&#39;,function () { 
          alert(123); 
        }); 
      }); 
    }) 
  </script> 
</head> 
<body> 
<input id="btn1" type="button" value="确认" /> 
<input id="btnBind" type="button" value="绑定按钮" /> 
</body> 
</html>

Such as the above code, if you click the 'btn1' button multiple times, then the click event will be bound to the 'btnBind' button as many times as possible, and on will be triggered as many times as it is bound.

Solution:

1. If you want it to be bound only once, you can first 'off' to unbind and then 'on'.

$(&#39;#btnBind&#39;).off(&#39;click&#39;).on(&#39;click&#39;,function () { 
  alert(123); 
});

2. Unbind() after executing it once

$(&#39;#btn1&#39;).click(function () { 
    $(&#39;#btnBind&#39;).on(&#39;click&#39;,function () { 
      alert(123); 
    });<BR>     $("#btnBind").unbind("click") 
});

The above example code of Jquery on binding event triggering multiple times is all the content shared by the editor. I hope It can give you a reference, and I hope you will support the PHP Chinese website.

For more Jquery on-bound events that trigger multiple instance codes, please pay attention to the PHP Chinese website for related articles!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn