简体   繁体   中英

global variable in jquery function doesn't work

I´ve defined a global variable in this function, but it doesn't work. If I define the variable in the function it works, but I want it global.

var currentpage = 1;

    $(document).ready(function(){

      function checkpage(currentpage) { 
        if (currentpage == 1) {
          $(".text_nav").html("some text");
        };
      }

      checkpage();

    });

Why do I want it? Because I want to decrease the variable on click to do something

$( "#button" ).click(function() {
  currentpage += 1;
});

//check currentpage variable again (who?)
            if (currentpage == 2) {
              $(".text_nav").html("some other text");
            };

It does work, you didn't send anything into the function, do this:

 checkpage(currentpage);

The currentpage in the function is a parameter, it's a local variable for that function and is separate from the global variable. Or simply remove the parameter if you don't need it:

function checkpage() { // Other than 'checkpage(currentpage)'
   ...
}

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