Gradislava Bikkulova
Gradislava Bikkulova

Reputation: 331

jquery, my variable has 2 values

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?

Upvotes: 0

Views: 75

Answers (2)

iappwebdev
iappwebdev

Reputation: 5910

You are executing your anonymous function two times. So there are two variables nb in different scopes. And your event handler is bound again after loading your view. So unbind it first:

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

I put event in a namespace .MyEventHandler to avoid to disable other click events. But actually you should better use the closest parent content as event listener. So:

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

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388416

It is because when you are removing #content, you are not removing the registered event handler.

You can do so by using .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);
    });
});

Upvotes: 0

Related Questions