简体   繁体   中英

Confused about global variable not updating

I have the following code:

var clickCount = 1;
var slideCount = $('div.slide').length;

$('a#next-button').click(function() {
    if(clickCount < slideCount) {
        $('div.slide').animate({"left":"-=" + slideWidth}, 'slow');
        clickCount = clickCount + 1;
    }
});

$('p').text(clickCount); 

It has a global variable called clickCount .

The $('a#next-button').click(function() { … updates the global variable with an increment of 1, each time the <a> element is clicked.

So, my question is, why does: $('p').text(clickCount); not show me the updated clickCount on the page everytine the <a> tag is clicked. Instead it just shows 1 (the original assigned value).

The variable is being updated, but your function ( $('p').text(clickCount); ) is only being run once, and thus only using the value it sees.

To fix this, put the $('p').text(clickCount); within the click function.

$('a#next-button').click(function() {
  if(clickCount < slideCount) {
     $('div.slide').animate({"left":"-=" + slideWidth}, 'slow');
     clickCount = clickCount + 1;
     $('p').text(clickCount); 
  }
});

You need to update the text of the paragraph each time the variable changes. The paragraph doesn't magically track the value of the clickCount variable :

$('a#next-button').click(function() {
    if(clickCount < slideCount) {
        $('div.slide').animate({"left":"-=" + slideWidth}, 'slow');
        clickCount = clickCount + 1;
        $('p').text(clickCount); 
    }
});

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