子页面–>父页面
- 变量:
parent.a
- 方法:
parent.getB()
- 查找父页面元素:
$('#id', window.parent.document) // #id为父页面元素(jq)
$('#btnOk', parent.document).click();
window.parent.document.getElementById("#id");
window.parent.document.getElementById("btnOk").click();
父页面–>子页面
- 变量:
$("#childframe").contentWindow.a;
document.getElementById("childframe").contentWindow.a;
- 方法:
$("#childframe").contentWindow.a();
document.getElementById("childframe").contentWindow.a();
- 元素:
$("#iframe中的控键ID",document.frames("framename").document).click();
$("#btnOk",document.frames("ifm").document).click();
$("#iframe的ID").contents().find("#iframe中的控件ID").click();
$("#ifm").contents().find("#btnOk").click();
window.frames["iframe的name值"].document.getElementById("iframe中控件的ID").click();
window.frames["ifm"].document.getElementById("btnOk").click();
var obj=document.getElementById("iframe的name").contentWindow;
var ifmObj=obj.document.getElementById("iframe中控件的ID");
ifmObj.click();
注:在本地测试的时候,出现如下错误:
ChildPage.html:10 Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
at btnClick (file:///C:/Users/hellosnowyy/Desktop/%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9%20(2)/ChildPage.html:10:24)
at HTMLInputElement.onclick (file:///C:/Users/hellosnowyy/Desktop/%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9%20(2)/ChildPage.html:18:68)
原因:跨页面操作涉及域的概念(origin),错误的意思是:未捕获的安全错误:阻止了一个域为null的frame页面访问另一个域为null的页面。代码运行时在本地直接用浏览器打开的,地址栏是file:///的页面,只需改为localhost访问就行(搭建本地服务器或者使用WebStorm)。
参考文档:
Uncaught DOMException: Blocked a frame with origin “null” from accessing a cross-origin frame.
Js/Jquery获取iframe中的元素 在Iframe中获取父窗体的元素方法