Javascript 使用 jQuery 捕获 iframe 重新加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11432448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:48:23  来源:igfitidea点击:

Catch iframe reload with jQuery

javascriptjquery

提问by LobsterMan

I have an iframe loaded dynamically with jQuery like this

我有一个像这样用 jQuery 动态加载的 iframe

jQuery('<iframe id="myFrame" src="iframesrc.php"></iframe>').load(function(){
    // do stuff when loaded
}).prependTo("#myDiv");

And I want to catch the reload event every time the inner frame is reloaded. I tried this:

我想在每次重新加载内部框架时捕获重新加载事件。我试过这个:

jQuery('body').on('load', '#myDiv', function() {
    alert('iframe loaded');
});

But I'm not getting any response, both on the initial load and when following links inside the iframe. What am I doing wrong?

但是在初始加载和跟踪 iframe 内的链接时,我都没有得到任何响应。我究竟做错了什么?

回答by Austin

You are looking for the loadaction of a div in your example above, not the iframe. Try:

您正在load上面的示例中寻找div的操作,而不是 iframe。尝试:

$("#myFrame").on("load", function () {
    alert("Hi there, hello");
})

Additionally, if you are not using other libraries, use $()to access jQuery as opposed to jQuery()

此外,如果您不使用其他库,请使用$()访问 jQuery 而不是jQuery()

Also note that any functions that you want to run on your page must be bound to jQuery's document ready event like so:

另请注意,您要在页面上运行的任何函数都必须绑定到 jQuery 的文档就绪事件,如下所示:

$(function () {
    // your code goes here
    $("#myFrame").attr("src", "http://google.com"); // <- this works
})

$("#myFrame").attr("src", "http://google.com"); // <- this does not work

回答by user2675617

for new url

对于新网址

location.assign("http:google.com");

The assign() method loads a new document.

assign() 方法加载一个新文档。

reload

重新加载

location.reload();

The reload() method is used to reload the current document.

reload() 方法用于重新加载当前文档。