我想在加载iframe几秒钟之后触发doSomething(),而是直接触发doSomething为什么?
<html>
<iframe id="myIframe" src="myFrame.html" width=100% height=600></iframe>
<script>
iframe = document.getElementById("myIframe");
function doSomething() {
alert("it should have wait 5000 milliseconds, instead it triggers immediately");
}
if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera) {
var oldonreadystatechange = iframe.onreadystatechange;
iframe.onreadystatechange = function(){
if (iframe.readyState == "complete"){
if (oldonreadystatechange != null) {
oldonreadystatechange();
setTimeout(doSomething(),5000);
}
}
};
} else {
var oldonload = iframe.onload;
iframe.onload = function(){
if (oldonload != null) {
oldonload();
}
setTimeout(doSomething(),5000);
};
}
</script>
</html>
答案 0 :(得分:2)
如果你想传递参数,一个非常简单的方法是为setTimeout创建一个新的匿名函数,如下所示:
setTimeout(function(){ doSomething(123, anotherParam) }, 5000);
那是因为在JavaScript中,如果将函数作为参数传递给另一个函数,那么someFunction(anotherFunction());您正在将该函数的执行结果传递给someFunction。
您要做的是将该函数的引用提供给setTimeout,以便setTimeout决定何时运行它。
这样做:
setTimeout(doSomething, 5000);
答案 1 :(得分:1)
除非我完全遗漏了某些内容,否则如果您只是触发iframe的加载事件,则可以使用以下代码来减少该代码:
document.getElementById('myIframe').onload = function() {
setTimeout(doSomething, 5000);
}
<强>段强>
<iframe id="myIframe" src="/" width=100% height=600></iframe>
<script>
iframe = document.getElementById("myIframe");
function doSomething() {
alert("it should have wait 5000 milliseconds, instead it triggers immediately");
}
iframe.onload = function() {
setTimeout(doSomething, 5000);
}
</script>
&#13;