我有一个页面在其中动态添加了iFrame。我想为每个iFrame捕获“ onLoad”事件。
因此,基本上,我想将事件附加到主体,但将其应用于每个子iFrame。这适用于其他事件,但似乎“传播”事件并未传播。
这是我到目前为止尝试过的:
$(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>
,它在jsfiddle上: https://jsfiddle.net/skeets23/qsrf802z/8/
有什么方法可以使它按预期工作?因此,我只能创建一个绑定并使它适用于任意数量的动态添加的iFrame?
答案 0 :(得分:1)
似乎要动态添加iframe,因此,最好的方法是捕获文档的DOMNodeInserted事件。请参阅以下示例:
$(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>
答案 1 :(得分:0)
将$(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>