利用iframe进行父页面和子页面的通信

来源:互联网 发布:webservice数据丢失 编辑:程序博客网 时间:2024/06/01 16:22

父页面parent.html:

<span id='parentSpan'>父页面元素</span><iframe src="child1.html" id='frame1'></iframe><br/><iframe src="child2.html" id='frame2'></iframe><br/><button onclick="getChildItem()">调用子页面方法</button><button onclick="getChildItem()">获取子页面元素</button>

调用子页面child1.html的方法,并获取其元素

function parentSay(){alert('say parent')}function getChildItem(){var child=document.getElementById('frame1').contentWindow;//第一种方法获取子页面//调用子页面的方法child.childSay();}function getChildItem(){var child=window.frames[0];//第二种方法获取子页面var childSpan=child.document.getElementById('childSpan');//获取子页面的元素alert(childSpan.innerHTML)}

子页面1, child1.html:

<span id='childSpan'>子页面1的元素</span><br/><button onclick="getParentFunction()">调用父页面方法</button><button onclick="getParentItem()">获取父页面元素</button>
子页面的方法:

function childSay(){alert('page1 function')}function getParentFunction(){var parent=window.parent;//获取父页面parent.parentSay();//调用父页面的方法}function getParentItem(){var parent=window.parent;var parentSpan=parent.document.getElementById('parentSpan');//获取父页面的元素alert(parentSpan.innerHTML)}

子页面1也可以与子页面2进行通信

child1中添加

function getPage3(){var parent=window.parent;//这里可以用parent.window获取父页面,在chrome测试过var page3=parent.document.getElementById('frame2').contentWindow;//通过父页面获取到父页面中的另一个子页面page3.childSay();//调用另一个子页面的方法}




原创粉丝点击