简体   繁体   English

相同脚本在点击事件javascript / jquery上加载了多次

[英]same script loading multiple times on click event javascript/jquery

$(document).click(function() {
  $('.settings').click(function(){
    alert();
  });

});

I am loading this script on click event as I cannot load this on ready event. 我装上这个脚本click事件,因为我无法加载此上ready的事件。 Now when I click on button with class settings first time, nothing happens as expected as the script is loaded after I click on button. 现在,当我第一次单击具有类settings按钮时,由于单击按钮后加载了脚本,因此没有发生任何预期的事情。

Second time, I click on this button, alert is shown one time (as expected). 第二次,我单击此按钮,警报显示了一次(如预期的那样)。

But the unexpected behavior is, when I click for third time, alert is shown 2 times. 但是意外的行为是,当我第三次单击时,警报显示2次。 When I click for 4th time, alert is shown 3 times and so on. 当我第四次单击时,警报显示3次,依此类推。

One possible reason that I can think of is, script was loading every time when I click. 我能想到的一个可能原因是,每次单击时脚本都在加载。

What could be the issue? 可能是什么问题? How can I prevent same piece of script from loading again and again? 如何防止同一脚本反复加载?

Thanks! 谢谢!

Each time you click, you add a new handler for .settings . 每次单击时,都会为.settings添加一个新的处理程序。 Try this: 尝试这个:

$(document).on('click', '.settings', function() {
  alert();
});

This issue will be solved if Click event related to document is fired for only one time when you click first time in settings button. 如果在设置按钮中单击第一次时,仅触发与文档相关的Click事件一次,则将解决此问题。

If you want an event handler to only fire once then take a look at .one(): http://api.jquery.com/one 如果您希望事件处理程序仅触发一次,请查看.one(): http : //api.jquery.com/one

 $(document).one("click",function() {
      $('.settings').click(function(){
        alert();
      });
    });

As @Bravo already suggested you need the off handler. 正如@Bravo已经建议您需要关闭处理程序。 You add a click event handler everytime you click. 您每次单击时都添加一个click事件处理程序。 So you should remove the previous click handler before adding another. 因此,您应在添加其他点击处理程序之前将其删除。 Something like: 就像是:

$(document).off('click').on('click', (function() {
  $('.settings').off('click').on('click', function(){
    alert();
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM