跨frame操作dom元素

时间:2023-03-08 21:20:38
跨frame操作dom元素

今天,一群友问到跨frame操作dom元素的问题。于是写了个demo,在此发表在博客里面,供其他同道中人参考!

创建child.html内容如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<title>每次点击按钮之后重新在浏览器地址栏回车</title>
<script type="text/javascript">
function setParentVal2Child_02(){
var txt = window.parent.document.getElementById("parent_01").value;
document.getElementById("child_01").value=txt;
}
function setChildVal2Parent_02(){
var txt = document.getElementById("child_02").value;
window.parent.document.getElementById("parent_02").value=txt;
}
</script>
</head>
<body style="background-color:red">
<input type="button" value="setParentVal2Child" onclick="setParentVal2Child_02()">
<input type="button" value="setChildVal2Parent" onclick="setChildVal2Parent_02()">
<p></p>
childVal_01:<input type="text" value="CCCC" id="child_01">
childVal_02:<input type="text" value="DDDD" id="child_02">
</body>
</html>

 创建index.html,内容如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<title>每次点击按钮之后重新在浏览器地址栏回车</title>
<script type="text/javascript">
function setParentVal2Child_01(){
var txt=document.getElementById("parent_01").value;
window.frames['child'].document.getElementById("child_01").value=txt;
}
function setChildVal2Parent_01(){
var txt=window.frames['child'].document.getElementById("child_02").value;
document.getElementById("parent_02").value=txt;
}
</script>
</head>
<body>
<input type="button" value="setParentVal2Child" onclick="setParentVal2Child_01()">
<input type="button" value="setChildVal2Parent" onclick="setChildVal2Parent_01()">
<p></p>
parentVal_01:<input type="text" value="AAAA" id="parent_01">
parentVal_02:<input type="text" value="BBBB" id="parent_02">
<p></p>
<iframe src="child.html" width="800" height="300" frameborder="1" name="child"></iframe>
</body>
</html>

 预览效果!如图:

跨frame操作dom元素

 

布局说明:红色部分为子frame。

功能说明:

点击"setParentVal2Child"按钮会把父frame里面的parentVal_01的值赋给childVal_01。

点击"setChildVal2Parent"按钮会把子frame里面的childVal_02的值赋给parentVal_02。

 

友情提示:

1.分别实现了在父frame和子frame里面进行子和父的传值操作!

2.window.parent获取直接父窗体,window.top获取*父窗体

3.源码见附件