简体   繁体   English

对全局变量没有更新感到困惑

[英]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 . 它有一个名为clickCount的全局变量。

The $('a#next-button').click(function() { … updates the global variable with an increment of 1, each time the <a> element is clicked. $('a#next-button').click(function() { …每次点击<a>元素时,以1为增量更新全局变量。

So, my question is, why does: $('p').text(clickCount); 所以,我的问题是,为什么: $('p').text(clickCount); not show me the updated clickCount on the page everytine the <a> tag is clicked. 没有在点击<a>标签的每一页上显示更新的clickCount。 Instead it just shows 1 (the original assigned value). 相反,它只显示1(原始指定值)。

The variable is being updated, but your function ( $('p').text(clickCount); ) is only being run once, and thus only using the value it sees. 该变量正在更新,但您的函数( $('p').text(clickCount); )仅运行一次,因此仅使用它看到的值。

To fix this, put the $('p').text(clickCount); 要解决这个问题,请输入$('p').text(clickCount); within the click function. click功能中。

$('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 : 该段落不会神奇地跟踪clickCount变量的值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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