javascript - 如何在加载 iframe 内容后立即运行函数?

标签 javascript html 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 内容加载后触发此操作(即无需等待应用程序中的其他内容)?我尝试用 document 替换所有 window 但它不起作用(它什么也不做)。

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

最佳答案

HTML

此方法仅使用 onload 属性在加载框架内容后调用该函数。

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

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

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

纯JS

如果 HTML 无法让您的船漂浮,您可以使用 onloadaddEventListener("load", ...),然后使用元素指针和 contentDocument 访问 iframe 内的元素(没有 IE?)

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

关于javascript - 如何在加载 iframe 内容后立即运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56873792/

相关文章:

JavaScript 图像映射不起作用(生成的 HTML 有效)

Java:匹配所有不以.htm结尾的字符串?”

html - 添加边距会弄乱下拉菜单的显示

javascript - 从 iFrame/Window 访问 JavaScript 中的父对象

javascript - 当涉及 iframe 时,获取返回按钮以在父页面上工作

html - Iframe 是我唯一的选择吗?

javascript - kendo ui 图表 donut 设置突出显示

javascript - 通过 Javascript 检查页面是否正在加载某些内容

javascript - 在reducer中使用map函数操作数组

html - CSS 布局技巧