javascript - 如何在加载 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 内容(即无需等待应用程序中的其他内容),有没有办法触发它?我尝试将所有替换为window
,document
但它不起作用(它什么也不做)。
我需要从 iframe 内部访问元素并更改它们的属性。
解决方案
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
你的船没有漂浮,你可以使用onload
oraddEventListener("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>
推荐阅读
- reactjs - laravel reactjs pusher:存在通道响应为302
- sql - 我得到的错误是'Msg 8120,'Vendors.VendorName' 在选择列表中无效'
- python - Python使用瀑布逻辑在多列上加入两个熊猫数据框
- java - 在 Java 中类型转换回用户定义的对象
- google-maps - Flutter GoogleMaps - 自定义标记的动态着色
- mysql - 我的 SQL 错误:错误 1064:您的 SQL 语法有错误;
- r - 如何找到r中数据子集的方差?
- python - 我的小程序需要帮助(python 列表)
- azure - Azure:如何关联特定 SQL 数据库的存储帐户?
- python-3.x - Keras-ValueError 中使用 YOLOv3 进行对象检测:如果您的数据是符号张量的形式