日期:2014-05-16  浏览次数:20309 次

js父页面操作的父子页面传值

对iframe来说,父页面访问子页面的方法用得最多的是XXX.contentWindow和frames[YYY]这样都可以得到子页面,区别在于,XXX对应的是iframe的id属性值,而YYY对应的是iframe的name属性值
看下面的例子:

<html>
<head>
<script language="javascript" type="text/javascript">
<!--
function setValue(obj,iframe){
?var $obj = getId(obj);
?var $iframe = getId(iframe);
?var getobj = $iframe.contentWindow.document.getElementById("getValue");
?//var getobj = window.frames[iframe].document.getElementById("getValue");
?if(!getobj){return}
?else{
??getobj.value = $obj.value;
??}
?}
function getValue(obj,iframe){
?var $obj = getId(obj);
?var $iframe = getId(iframe);
?var setobj = $iframe.contentWindow.document.getElementById("setValue");
?//var setobj = window.frames[iframe].document.getElementById("setValue");
?if(!setobj){return}
?else{
??$obj.value = setobj.value;
??}
?}

然后再新建一个1.html里面加上一个<input name="" type="text" id="getValue">
和2.html,里面加上<input name="" type="text" id="setValue">
然后看看效果!~

function getId(id){
?var $ = document.getElementById(id);
?return $;
?}

–>
</script>
</head>

<body>
<a href=”1.html” target=”iframe1″>跳到1.html</a>
<a href=”2.html” target=”iframe1″>跳到2.html</a><br>
<input name=”" type=”text” id=”parenttext” value=”把我传到子页面”>
<input type=”button” value=”父传子” onClick=”setValue(’parenttext’,'iframe1′)”>
<input type=”button” value=”子传父” onClick=”getValue(’parenttext’,'iframe1′)”><br>
<iframe id=”iframe1″ name=”iframe1″ frameborder=”0″ scrolling=”0″ style=”width:300px; height:150px; border:1px #009966 solid;” src=”1.html”></iframe>
</body>
</html>

通常在很多情况下都会遇到通过js来传值的问题,只要通过一些页面关联,他们的值就可以互相传递
其中应用框架的时候传值问题可能会遇到更多一些

  1、从父页面传值到子页面可能很容易办到,在很多情况下可以不通过js来传就可以达到目的,但从子页面把数据传给父页面就不是那么容易了,其实思路很简单,首先你要通过父页面找到子页面,按照W3C标准来,语法如下:
document.getElementById(”iframe1″).contentWindow;
取到子页面对象

  2、此文为了达到一个很醒目的效果,做了一个很即时的例子,当鼠标选中子页面的任何文字的时候,父页面的text里面就把显示出来,通过 getSelection和selection.createRange方法来实现,关于selection.createRange是只能在ie6上面 能用,所以要加。

  3、注:此实例牵涉到一个安全机制问题,以前很多浏览器都没考虑到过的,所以这个实例在一部分浏览器里面调试不起作用,但不用担心,你把代码放到自己的机子上试试,是得行的,也就是说这个跨服务器去执行这样的操作就会出问题。

?<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>无标题文档</title>? </head>? <body> <input type="text" id="text1"><iframe src="http://www.uideas.cn/download/demo1.html " id="iframe1" name="iframe1" style="width:60%; height:60%;"></iframe> </body>? </html> <script language="JavaScript"> var childHtml = document.getElementById("iframe1").contentWindow; var parentText = document.getElementById("text1"); var getValue = ""; if(childHtml.document.selection){ ?childHtml.document.onmouseup=function(){ ??parentText.value = childHtml.document.selection.createRange().text; ??} ?}else{ ??childHtml.onmouseup=function(){ ??parentText.value=childHtml.window.getSelection(); ??} ?}</script>

喜欢的朋友可以查考下。