什么会改变 iframe 的来源?如果您有权访问该代码,那么您可以执行 onload 函数中的任何操作。
如果链接将其 target 属性设置为 iframe,并且这就是源的变化方式,那么您可以劫持链接点击:
$('a[target="frameB"]').bind('click', function () {
//run your onload code here, it will run as the iframe is downloading the new content
});
另外,顺便说一句,您可以像这样在 jQuery 中为 load 事件绑定一个事件处理程序:
$('#frameB').bind('load', function () {
//run onload code here
});
更新
站点 -> 框架B -> 框架A
$("#frameB").contents().find("#frameA").bind('load', function () {
//load code here
});
这会选择#frameB 元素(即在当前顶级DOM 中),获取它的内容,找到#frameA 元素,然后为load 事件绑定一个事件处理程序。
请注意,此代码必须在 #frameB 加载了其 DOM 中已存在的 #frameA 元素后运行。这样的事情可能是个好主意:
$('#frameB').bind('load', function () {
$(this).contents().find('#frameA').bind('load', function () {
//run load code here
});
});
更新
要劫持#frameB 元素中的链接:
$('#frameB').contents().find('a[target="frameA"]').bind('click', function () {
/*run your code here*/
});
这将在#frameB 元素中找到其target 属性设置为frameA 的任何链接,并添加click 事件处理程序。
同样,这仅在 #frameB iframe 元素已加载(或至少到达 document.ready 事件)时才有效,因此您可以选择它的元素。