在Javascript中组装var

时间:2013-07-24 11:58:28

标签: javascript

这是在超时功能中循环。 nw保持未定义或在每次新启动时再次重置为undefined。那是为什么?

$("#wert"+i).load('variable.html #w'+i);
if(! nw){
alert(nw);
var nw = eval('neuerwert'+i); // Here I set the var nw, so why is it undefined again the next time around?
}
if ($("#w"+i).html() != nw){
wertaenderung('#wert'+i);
nw = $("#w"+i).html();
};

3 个答案:

答案 0 :(得分:1)

变量nw必须在正确的范围内:

var nw;
$("#wert"+i).load('variable.html #w'+i);
if(! nw){
    alert(nw);
    nw = eval('neuerwert'+i);
}
if ($("#w"+i).html() != nw){
    wertaenderung('#wert'+i);
    nw = $("#w"+i).html();
};

你在声明它之前使用了变量

答案 1 :(得分:1)

尝试将nw移出加载函数:

var nw;
$("#wert" + i).load('variable.html #w' + i);
if (!nw) {
    alert(nw);
    nw = eval('neuerwert' + i);
}
if ($("#w" + i).html() != nw) {
    wertaenderung('#wert' + i);
    nw = $("#w" + i).html();
};

答案 2 :(得分:1)

只需删除此行中的“var”:

var nw = eval('neuerwert'+i);

因此,您将在全局上下文中初始化nw变量。

通过编写var nw = ...,您可以创建一个在离开回调函数时被删除的局部变量。