防止 jQuery 中的双重事件绑定

Preventing double event binding in jQuery

我有这个代码

$(".generate").click(function() {
    $.getJSON("jsonfile.json").done(function(data) {

        if (parseInt(data)>0) {
            $(".mybutton").click(function() {
               alert(data); 
            });
        }

    });
});

单击 "generate" 按钮时,将调用 getJSON 函数,如果数据显示 "ok",则我可以按 "mybutton" 提醒数据;

唯一的问题是,如果我按几次 "generate" 按钮(我希望发生这种情况),"mybutton" 也会多次提醒 "hello"(取决于我点击了多少次生成按钮)。

我试过 e.stopPropagation(),但这没有帮助。

使用委派 on() 喜欢

    $(function() {
     var buttonData = {};
     $(".generate").click(function() {
         $.getJSON("jsonfile.json").done(function(data) {

             if (parseInt(data) > 0) {
                 buttonData = data;
             }

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

并将其绑定到 getJSON 成功处理程序之外

您可以每次解除绑定并重新绑定处理程序

if (parseInt(data)>0) {
    $(".mybutton").off('click').click(function() {
       alert(data); 
    });
}

如果你这样试试呢? (没有测试这个,但应该可以)

$(".generate").click(function() {
   $(this).unbind('click').next()
    $.getJSON("jsonfile.json").done(function(data) {

        if (parseInt(data)>0) {
            $(".mybutton").click(function() {
               $(this).unbind('click').next()
               alert(data); 
            });
        }

    });
});

原因是每次单击按钮 .generate 时,都会在具有 class .mybutton

的元素上添加一个新的事件处理程序

不太清楚你想做什么,但如果目的是存储你从 ajax 调用中获得的数据,你可以这样做:

//data container
var localData;

//will show the actual content of the variable when .mybutton is clicked
$(".mybutton").click(function()
{
    alert(localData);
});

//this will update the variable when .generate is clicked
$(".generate").click(function() 
{
    $.getJSON("jsonfile.json").done(function(data) 
    {
        if (parseInt(data)>0)
        {
            localData = data; 

            //this will trigger the click event on the button .mybutton that will fire the handler with the alert
            $(".mybutton").trigger('click'); 
        }
    });
});

为什么总是重新绑定事件。单击生成按钮后,按钮是否已从 DOM 中删除?

否则,您只能绑定一次事件,然后在没有可用数据时禁用按钮:

$(".mybutton").prop('disabled', true); // initially disable
$(".mybutton").click(function() { // bind the event once
    alert(data); 
});

$(".generate").click(function() {
    $(".mybutton").prop('disabled', true); // disable if new data starts to generate
    $.getJSON("jsonfile.json").done(function(data) {

       if (parseInt(data)>0) {
           $(".mybutton").prop('disabled', false); // enable if everything is ok
       }
   });  
});