下面是我的Javascript文档,它在$(document).ready()中运行。Javascript是从我的站点的页脚加载的。为了简化,我用[...]代替了不相关的代码。
// When the document is ready, run the display scripts
$(document).ready(function() {
// Define the frame height functions
function getDocHeight(doc) {
[...]
}
document.domain = 'mysite.com';
function resizeIframe() {setIframeHeight('date-price-book');}
function setIframeHeight(ifrm) {
[...]
}
function AutoResize() {
resizeIframe();
resizeIframe();
setTimeout("AutoResize()", 500);
}
AutoResize();
[... more Javascript code...]当我运行页面时,我得到错误:Uncaught ReferenceError: AutoResize() is not defined。
我可以通过注释掉AutoResize();行(上面示例代码中的最后一行)来阻止这个错误的发生。但是为什么会抛出这个错误呢?AutoResize()函数肯定是在它的上一行中定义的吧?
谢谢你的帮忙!
发布于 2012-08-03 03:10:19
setTimeout("AutoResize()", 500);当执行上面的setTimeout时,它对全局范围内的字符串求值。AutoResize()隐藏在闭包中,因此找不到它。
使用名称指定对函数的引用。
setTimeout(AutoResize, 500);其他选项是闭包
setTimeout(function() { AutoResize(); }, 500);如果想要向函数发送参数,可以使用closure方法。
发布于 2012-08-03 03:10:38
因为您是在$(document).ready(function () { ... } );闭包中定义AutoResize,所以它不是全局可用的(这很好)。
如果在调用setTimeout时使用字符串而不是函数引用(这很糟糕),则会假设字符串将解析到的函数调用是全局可用的(因为setTimeout在window/global作用域中运行)。
发布于 2012-08-03 03:20:00
我没有把握。当我尝试这部分的时候,它起作用了。
function AutoResize(){
console.log('test');
setTimeout('AutoResize()',1000);
}
AutoResize();也许是其他地方出了问题。
https://stackoverflow.com/questions/11784113
复制相似问题