简体   繁体   中英

Reset Variable Counter after a fresh AJAX request. JavaScript/jQuery

Sorry If this Question is Trivial!! Well, I've a Page where I'm loading contents with AJAX.

Main Page (index.html):

<a href="#" id="loadContent">Load Remote Page</a>

<div id="ajaxContent">

//Loads AJAX contents Here!!

</div>

Remote Page (remote.html):

<h2 id="counter"></h2>
<button class="counterPlus" type="button">++</button>

jQuery (script.js):

$("#loadContent").on("click", function(){

        $.ajax({
                url: "remote.html",
                type: "GET",
                success: function(data){
                          $("#ajaxContent").html(data);
                }
        })

});

var counter = 1;
$("#ajaxContent").on("click", ".counterPlus", function(){
    console.log(counter);
    counter = counter + 1;
    $("#counter").text(counter);
});

On clicking the link in the Loaded page, I can see incremented value but the problem is Counter is not resetting After a fresh AJAX load (Click on the Link). I'm aware that old Variable value stays in Memory But What is the Solution to reset the Counter in this kinda Problem??

That's because your variable counter has global scope.

Just reset it inside the success callback function of ajax call.

var counter = 1;
$("#loadContent").on("click", function(){

    $.ajax({
            url: "remote.html",
            type: "GET",
            success: function(data){
                      counter = 1;
                      $("#ajaxContent").html(data);
            }
    })
});

$("#ajaxContent").on("click", ".counterPlus", function(){
    console.log(counter);
    counter = counter + 1;
    $("#counter").text(counter);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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