简体   繁体   English

防止js函数多次运行

[英]Prevent js function running multiple times

Newbie here.. 新手在这里..

I have a js function that runs 3 times due to I have call the function 3 times.. 我有一个js函数可以运行3次,因为我已经调用了3次。

var deleteFunc = function() {
   $('.delete').on('click', function(){
      // ajax code here...
   });
};

(loadData = function(){
   // this will be in a loop didn't place its because it too long
   var content = '<tr><td>1</td><td>John</td><td><span class="delete">Delete</span></td></tr>';

   $('#first_tbl').append(content);

   deleteFunc();
})();

(loadSecondData = function(){
   // this will be in a loop didn't place its because it too long
   var content = '<tr><td>1</td><td>John</td><td><span class="delete">Delete</span></td></tr>';

   $('#second_tbl').append(content);

   deleteFunc();
})();

(loadThirdData = function(){
   // this will be in a loop didn't place its because it too long
   var content = '<tr><td>1</td><td>John</td><td><span class="delete">Delete</span></td></tr>';

   $('#third_tbl').append(content);

   deleteFunc();
})();

When I click the .delete the deleteFunc() will run 3 times. 当我单击.deletedeleteFunc()将运行3次。

I have an idea that I will create 3 delete function like deleteFunc() deleteSecondFunc() deleteThirdFunc() , but I notice that it will be redundant since it has same functionality and code. 我有一个想法,我将创建3个删除函数,如deleteFunc() deleteSecondFunc() deleteThirdFunc() ,但是我注意到它会多余,因为它具有相同的功能和代码。

Can anyone help me how to fix this? 谁能帮我解决这个问题?

Remove the previous binding and then add new one. 删除以前的绑定,然后添加新的绑定。

var deleteFunc = function() {
    $('.delete').off('click').on('click', function(){
       // some ajax code here...
    });
};

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

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