简体   繁体   中英

Load Function not updating Global Variable

I'm creating a node application and having trouble updating a global variable.

Here is my code (ejs file):

 <% include ../partials/header %>

    <div class="page container">
        <div id="campgroundsRow" class="row">
        </div> <!-- row end -->
        <button id="loadMore">Load More</button>
    </div> <!-- Container End -->
    <% include ../partials/footer %>

    <script>
        var numGroundsToLoad = 1;
        var numGroundsLoaded = 0;

        loadCampgrounds(numGroundsLoaded, numGroundsToLoad);

        function loadCampgrounds(numGroundsLoaded, numGroundsToLoad) {
              var grounds = <%-JSON.stringify(campgrounds) %>
              for(var i=numGroundsLoaded + 1; i<numGroundsLoaded + numGroundsToLoad; i++) {
                   //code to add grounds[i] to campgroundsRow div
              }
              numGroundsLoaded += numGroundsToLoad;
        }

        $("#loadMore").on("click", function() {
              loadCampgrounds(numGroundsLoaded, numGroundsToLoad);   
        });
    </script>

The problem I'm having is the loadCampgrounds function is not actually updating numGroundsLoaded . So when I click the load more button ( #loadMore ), it thinks that I am adding ground[0].

What I want is that each time I click load more, the next ground is added. Ie, ground[0] gets added by default. Then on load more, ground[1] . Then on load more, ground[2] and so on (assume there are unlimited grounds for now).

As you can see, the problem is related to both scope and when stuff is being loaded.

Because you update the local variable. In this case, to update global variable you need to access it through window.numGroundsLoaded .

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