setInterval和window.onload问题 [英] setInterval and window.onload problem

查看:126
本文介绍了setInterval和window.onload问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码

window.onload = function() {            
    function foo() {
        alert("test");
    }
    setInterval("foo()",500)
}

返回undefined ...当我在window.onload之外使用它时,它可以工作。谁能解释一下为什么?

Which returns undefined...When i use it outside the window.onload it works. Can anyone explain me why?

推荐答案

中使用字符串命令setInterval()将尝试在全局(窗口)范围内查找该函数,但由于该函数是在本地范围内定义的,因此将无法找到该函数。您应该将函数本身传递给 setInterval()

Using a string command in setInterval() will try to look for the function in the global (window) scope, but since the function is defined in a local scope, it won't be found. You should pass the function itself to setInterval() instead.

window.onload = function() {            
    function foo() {
        alert("test");
    }
    setInterval(foo, 500);
}

这篇关于setInterval和window.onload问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆