简体   繁体   English

在页面上为每个iFrame添加`load`事件

[英]add `load` event for EVERY iFrame on a page

I have a page that has dynamically added iFrames in it. 我有一个页面,其中已动态添加了iFrame。 I want to catch the "onLoad" event for every iFrame. 我想为每个iFrame捕获“ onLoad”事件。

So basically, I want to attach the event to the body but have it apply to every child iFrame. 因此,基本上,我想将事件附加到主体,但将其应用于每个子iFrame。 This works for other events, but it seems like the "load" event isn't propagating. 这适用于其他事件,但似乎“传播”事件并未传播。

Here's what I've tried so far: 到目前为止,这是我尝试过的方法:

 $(document).on("load", "iframe", function() { $("body").append("this is what I want, but it doesn't work!"); }); var iFrame = $("<iframe/>", { srcdoc : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>" }); $("body").append(iFrame); iFrame.on("load",function(){ $("body").append("this seems to work.... but isn't what I'm looking for."); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

and here it is on jsfiddle: https://jsfiddle.net/skeets23/qsrf802z/8/ 并且它在jsfiddle上: https ://jsfiddle.net/skeets23/qsrf802z/8/

Any way to get this working as expected? 有什么办法可以使此工作按预期进行吗? So I can just create one binding and have it work for any number of dynamically added iFrames? 因此,我只能创建一个绑定并使它适用于任意数量的动态添加的iFrame?

Seems you want to add iframe dynamically, so, best method is catch event DOMNodeInserted of document. 似乎您想动态添加iframe,因此,最好的方法是捕获文档的DOMNodeInserted事件。 See example follow: 请参阅以下示例:

 $(document).on('DOMNodeInserted', function(e) { //check is iframe is loaded if(e.target.localName=="iframe"){ console.log("New iframe loaded!"); $("div").append("this does NOT seem to work!"); }; }); function addIframe(){ var iFrame = $("<iframe />", { srcdoc : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>" }); $("body").append(iFrame); iFrame.on("load",function(){ $("div").append("this seems to work...."); }); }; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="addIframe();">Add Iframe</button> <div> </div> 

Change $(document).on("load" ... to $("iframe").on("load", ... . And place it at end of script, it will work! $(document).on("load" ...更改$("iframe").on("load", ...并将其放在脚本末尾,它将起作用!

 var iFrame = $("<iframe />", { srcdoc : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>" }); $("body").append(iFrame); iFrame.on("load",function(){ $("div").append("this seems to work...."); //alert("cde"); }); $("iframe").on("load", function () { $("div").append("this does NOT seem to work!"); alert("abc"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM