“功能未定义"在 setTimeout 中调用 document.write 之后? [英] "function is not defined" after document.write called in setTimeout?
问题描述
代码如下:
function getTime(j){
var stopClock= new Date();
delta[parseInt(j)]=stopClock.getMilliseconds()-start.getMilliseconds();
}
//REST OF THE CODE!!
function func(){
{
for (var i = 0; i < 6; i++){
start = new Date();
document.write('<img src="'+URL[i]+'" width="1" height="1" alt="" onload="getTime('+i+');"/>');
}
}
//SOME CODE
setTimeout(function() {
func();
},100);
但是我收到了这个错误:getTime is not defined
However I got this error: getTime is not defined
如果我像这样声明 getTime:
if I declare getTime like this:
document.getTime= function (j)
没有错误,但它从不执行该函数.
There is no error but it never execute that function.
如果我删除了 setTimeout,它就可以正常工作了.
If I remover the setTimeout, it will work with no problem.
有什么想法吗?
谢谢,
推荐答案
您正在使用 document.write
调用破坏 DOM.在某些浏览器中,这也会破坏全局变量.
You're destroying the DOM with your document.write
call. In some browsers, this also destroys global variables.
代替document.write
,试试...
for (var i = 0; i < 6; i++){
var img = document.body.appendChild(document.createElement('img'));
img.src = URL[i];
img.width = 1;
img.height = 1;
img.onload = makeHandler(i);
}
<小时>
function makeHandler(i) {
return function() {
getTime(i);
};
}
<小时>
以下是清除全局变量的简单演示...
Here's a simple demonstration of the globals being cleared...
在 Firefox 中,第二个警报将是 undefined
.在 Chrome 中,全局保留.
In Firefox, the second alert will be undefined
. In Chrome, the global is retained.
window.foo = 'bar';
alert(window.foo); // now we have it
setTimeout(function() {
document.write('new content');
alert(window.foo); // now we don't
}, 100);
这篇关于“功能未定义"在 setTimeout 中调用 document.write 之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!