开发者

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 wi开发者_JS百科th 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); 
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜