var t = 0;
function addDiv()
{
var div = document.createElement("div");
t++;
div.setAttribute("id", "box" + t);
document.body.appendChild(div);
AddStyle();
}
var h = 0;
var p = 1;
function doMove()
{
var okj = document.getElementById("box" + p);
if (p <= t) {
p++;
}
var g = setInterval(function () {
var go = parseInt(okj.style.left, 0) + 1 + "px";
okj.style.left = go;
}, 1000 / 60);
}
我的问题是,在p + p递增后,每次调用var p = 1
时我的doMove
会递增吗?请帮我解决这个问题。
答案 0 :(得分:2)
根据定义,全局变量具有全局范围,因此您可以递增它们或在函数内重新分配它们并且这将起作用,这太棒了!
虽然Borgtex指出你的if
陈述不起作用
if (p <= t) {
p++;
}
您已在另一个函数中声明变量t
,因此您的doMove()
函数无权访问它,因此此语句将始终返回false
;如果您将t
设为全局变量或将其作为参数传递给doMove()
函数,那么这将有效。
var p = 1; // this variable is global
function varTest(){
p++ //This will work because p is global so this function has access to it.
var t = 0;
}
function anotherTest(){
if(p<t){ //This will return false - t is not in scope as it was defined in another function
alert("supercalifragilisticexpihalitoscious");
}
}