首页 > 解决方案 > 如何在加载 iframe 的内容后立即运行函数?

问题描述

我目前正在使用:

function printThing(){ 
    let link = parent.document.getElementById("oLink").href; 
    console.log(link); 
}

if (window.attachEvent) {window.attachEvent("onload", printThing);} 
else if (window.addEventListener) {window.addEventListener("load", printThing, false);} 
else {document.addEventListener("load", printThing, false);}

从 iframe 的内容中获取链接(使用 srcdoc 而不是 src)并在控制台中打印它。在发送到前端之前,此代码将被添加到一些存储的 html 中。

一旦加载 iframe 内容(即无需等待应用程序中的其他内容),有没有办法触发它?我尝试将所有替换为windowdocument但它不起作用(它什么也不做)。

我需要从 iframe 内部访问元素并更改它们的属性。

标签: javascripthtmliframe

解决方案


HTML

onload一旦加载了框架的内容,此方法仅使用该属性来调用该函数。

<iframe id="some_frame" onload="on_iframe_load(this)">
    ....
</iframe>

显然,请确保该on_iframe_load(_this)函数在您的 JS 代码中。为了进一步解释为什么我们传入this,请on_iframe_load()理解this从 DOM 元素传递将传递对元素的引用。

<script>
var on_iframe_load(_this) = () => {
    _this.contentDocument.getElementById("something_in_this_frame").doWhatever(...);
}
</script>

纯JS

如果HTML你的船没有漂浮,你可以使用onloadoraddEventListener("load", ...)然后iframe使用元素指针访问里面的元素和contentDocument(没有 IE?)

<script>
document.getElementById("some_frame").onload = function() { // or you could use `addEventListener("load", function(){...})`
    this.contentDocument.getElementById("some_element_in_frame").doThing(...)
}
</script>

推荐阅读