您的位置:首页 > 其它

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

2017-08-17 09:43 295 查看
父页面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.par
4000
ent;//这里可以用parent.window获取父页面,在chrome测试过
var page3=parent.document.getElementById('frame2').contentWindow;//通过父页面获取到父页面中的另一个子页面
page3.childSay();//调用另一个子页面的方法
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: