0

in a page test.php I'm loading content.php like this:

$(document).on('click', '.test', function () {
        $('#content').load('content.php');
}); 

in content.php I have this Jquery code:

$(function() {
   var nb = 10;
   $(document).on('click', '.trigger', function () {
         alert(nb);
         nb +=10;
   });
   $(document).on('click', '.exit', function () { $('#content').html(''); });
});

when I'm clicking for the first time on #content nb as the value 10 and I can increment it by clicking on it, for exemple I'm clicking 3 times on it so its value is 40. Then I'm closing the div by clicking on .exit, and I'm reloading content.php by clicking on #content. Now I have two alert: nb as the value 10 but it also has the value 40, how come it still has the value 40?

4

2 回答 2

1

您正在执行您的匿名函数两次。nb所以在不同的范围内有两个变量。加载视图后,您的事件处理程序将再次绑定。所以先解绑:

$(document).off('click.MyEventHandler').on('click.MyEventHandler', '.trigger', function () {
     alert(nb);
     nb +=10;
});

我将事件放在命名空间.MyEventHandler中以避免禁用其他点击事件。但实际上你最好使用最近的父内容作为事件监听器。所以:

$('#content').off('click.MyEventHandler').on('click.MyEventHandler', '.trigger', function () {
     alert(nb);
     nb +=10;
});
于 2013-03-19T09:37:48.180 回答
0

这是因为当您删除时#content,您并没有删除已注册的事件处理程序。

你可以通过使用.off来做到这一点

$(function() {
    var fn = function() {
        alert(nb);
        nb += 10;
    };

    var nb = 10;

    $(document).on('click', '.trigger', fn);
    $(document).on('click', '.exit', function() {
        $('#content').html('');
        $(document).off('click', '.trigger', fn);
    });
});
于 2013-03-19T09:38:17.537 回答