我的目标是让父页面将 iframe 的 src 从空白更改为其正确的 url(以便在给定点利用 iframe 中的 onload 处理程序,但这不是重点),然后操作 iframe 的内容。然而,当 DOM 加载时,javascript 似乎忽略了 iframe 中不在其 src 上的任何元素。有什么办法可以解决这个问题吗?
setTimeouts 旨在允许 DOM 和 iframe 加载。 编辑:修复了一些东西。 这是包含页面:
<html><head>
<script type="text/javascript">
var done = false;
var theIframe;
window.onload = function () {
setTimeout('stuff()', 2000);
clearTimeout('stuff()');
}
function stuff() {
if (!done) {
theIframe = window.myiframe;
theIframe.src = 'http://localhost/TestStuff/redirectIframe.jsp';
done = true;
stuff();
} else {
theIframe.setMe = true;
}
}
</script>
</head>
<body>
<iframe src="" width="500" height="500" id="myiframe" name="myiframe">
</iframe>
</body>
这是 iframe:
<html>
<head>
<script type="text/javascript">
var setMe = false;
window.onload = setInterval('checker()', 1000);
function checker() {
alert('hi');
if (setMe) {
window.onload = null;
top.location = 'http://www.google.com';
alert('foundit');
} else alert('a');
}
</script>
</head>
<body></body>
</html>
有什么想法吗?
最佳答案
在这段代码中:
theIframe.src = ...;
stuff();
您立即调用 stuff()
,与您所描述的相反,因此实际上您不允许任何时间加载页面。也许您对 setTimeout
的工作原理感到困惑:它只是在指定时间后安排一次执行,它不会自动延迟对函数的所有调用。
此外,您只能将 clearTimeout
与 setTimeout
返回的先前 ID 一起使用,而不是像现在这样使用代码。
尝试这样的事情:
window.onload = function() {
loadFrame();
}
function loadFrame() {
theIframe = ...;
theIframe.src = ...;
setTimeout(setSomething, 2000);
}
function setSomething() {
theIframe.setMe = true;
}
关于javascript - 可以设置 iframe 的 src 并随后操作其内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5162823/