我复制了 Mozilla 文档中关于 setInterval() ( https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval?redirectlocale=en-US&redirectslug=DOM%2Fwindow.setInterval#Example_1.3A_Generic ) 的示例#2,但在我的 JSFiddle 中,文本的颜色不会在红色和蓝色之间交替:
演示:http://jsfiddle.net/lpsternotes/JHpt9/
这不可能是因为我需要 jQuery 或标记,对吧?我完全复制过来了。
我还想请求澄清:原因 var nIntervId;在顶部被定义为全局变量,这样它就可以在changeColor()和stopTextColor()函数中使用,对吗?
var nIntervId; //global variable
function changeColor() {
nIntervId = setInterval(flashText, 500);
}
function flashText() {
var oElem = document.getElementById("my_box");
oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
function stopTextColor() {
clearInterval(nIntervId);
}
换句话说,如果代码如下所示:
function changeColor() {
var nIntervId = setInterval(flashText, 500);
}
function flashText() {
var oElem = document.getElementById("my_box");
oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
function stopTextColor() {
clearInterval(nIntervId); //undefined??
}
最佳答案
您的函数在另一个函数中定义(在 onLoad
中执行)(根据左侧 JSFiddle 选项中的第二个下拉菜单)。
这意味着它们的范围仅限于该函数,而不是全局变量。
因此,它们超出了 onload="stopTextColor();"
属性的范围。
只需在现有 onload 处理程序中调用 stopTextColor()
,而不是在使用 onload
属性创建的另一个处理程序中调用。
关于javascript - Javascript Mozilla 文档中的 setInterval() 示例在 JSFiddle 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19080342/