我动态创建了一个iframe,发现这个iframe触发了两次onload事件。
var i=0;
frameOnload=function(){
console.log(i++);
};
var ifr=document.createElement("iframe");
ifr.src="javascript:(function(){document.open();document.write('test');document.close();})();";
ifr.onload=frameOnload;
document.body.appendChild(ifr);
为什么我最后是1?
如何防止iframe的onload两次而不是将onload函数指向自身内部的null?
最佳答案
我也遇到了同样的问题,但是没有得到答案,所以我自己测试了一下。
如果您在 iframe 附加到正文之前附加 onload 事件,则 iframe onload 事件将在 webkit 浏览器 ( safari/chrome ) 中触发两次。
因此,您可以通过按以下方式更改代码来阻止 iframe 加载两次。
document.body.appendChild(ifr);
ifr.onload=frameOnload; // attach onload event after the iframe is added to the body
那么,你只会得到一个onload事件,这是文档真正加载的事件。
关于javascript - 动态创建的iframe触发onload事件两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10781880/