一旦定义的变量始终未定义

时间:2014-07-29 12:06:37

标签: jquery

$('.btnsG img').click(function(){
    if(typeof indexT === 'undefined') {var indexT = 1};
    indexT += 1;
    alert (indexT);
});

加载页面后,第一次点击提醒为2,那没关系。

每次下一次点击后,我希望逐渐将变量更改为3-4-5 ......因为它现在不是未分解的,但警报会继续显示值2

有什么问题?

2 个答案:

答案 0 :(得分:2)

您正在范围中启动变量,这意味着它是一个局部变量。点击事件后,您的变量将不会为futur事件定义。

将它移到你的处理程序之外:

var indexT = 1;
$('.btnsG img').click(function(){
    indexT += 1;
    alert (indexT);
});

你在这里处理的是功能关闭。您正在单击处理程序中定义变量。这意味着futur事件将无法访问该变量。让我们逐行处理您的代码:

$('.btnsG img').click(function(){ //Bind click event. You pass an anonymus function, creating a scope ON EVERY CLICK
    if(typeof indexT === 'undefined') //Check for var indexT in current and parent scopes. That variable is not define in any scope.
        var indexT = 1; //Assign indexT in the current scope (the one created every click)
    indexT += 1; //Add 1 to the variable.
    alert (indexT); //Alert
}); //Close the function, close the scope. Reference to indexT lost forever.

因此,变量indexT仅在点击事件中定义,一旦该事件结束,就会消失

现在让我们看看解决方案:

var indexT = 1;//Create a variable in that scope (currently the global scope) <------------------------------------------
$('.btnsG img').click(function(){ //Bind click event. You pass an anonymus function, creating a scope ON EVERY CLICK    |
    indexT += 1; //Add one to the first variable hit named indexT in the current and parent scope, which is this one ----
    alert (indexT);
}); //Close the click event scope

现在变量在较高的范围内定义,这意味着它不会在每次点击时定义,而是在页面加载时定义。

答案 1 :(得分:1)

尝试从该函数中声明变量,只是将其范围限制在该函数内部,它会导致每次调用函数时重新声明该变量。

var indexT = 1;  
$('.btnsG img').click(function(){
    indexT++;
    alert (indexT);
});