父元素与子iframe相互获取变量和元素对象的具体实现

父元素与子iframe相互获取变量和元素对象的方法有很多,本文提供了一些不错的示例另收集网上的一些,可以参考下

 
 
父中: 
复制代码代码如下:

<input id="username"type="text" /> 
<scripttype="text/javascript"> 
var count = 1; 
</script> 

------------------------------------------------------------- 
子iframe中: 
复制代码代码如下:

<scripttype="text/javascript"> 
alert(window.parent.count); //获取父中的js变量 
alert($("#username", window.parent.document));//获取父中jQuery对象 
alert(window.parent.document.getElementByIdx_x('username'));//获取父中DOM对象 
</script> 

-------------------------------------------------------------------------------------------------- 

子iframe中(id="iframeId"name="iframeName"): 
复制代码代码如下:

<input id="username"type="text" /> 
<scripttype="text/javascript"> 
varcount = 1; 
</script> 

------------------------------------------------------------- 
父中: 
复制代码代码如下:

<scripttype="text/javascript"> 
alert(document.iframeName.count);//获取子iframe中的js变量 
alert($(window.frames["iframeName"].document).contents().find("#username"));//获取子iframe中jQuery对象 
alert($("#username",document.frames("iframeName").document));//获取子iframe中jQuery对象 
alert(window.document.getElementById('iframeId').contentWindow.document.getElementByIdx_x('username'));//获取子iframe中DOM对象 
</script> 

收集网上的一些示例: 
用jQuery在IFRAME里取得父窗口的某个元素的值 
只好用DOM方法与jquery方法结合的方式实现了 

1. 在父窗口中操作 选中IFRAME中的所有单选钮 
$(window.frames["iframe1"].document).find("input:radio").attr("checked","true"); 
2. 在IFRAME中操作 选中父窗口中的所有单选钮 
$(window.parent.document).find("input:radio").attr("checked","true"); 
父窗口想获得IFrame中的Iframe,就再加一个frames子级就行了,如: 
$(window.frames["iframe1"].frames["iframe2"].document).find("input:radio").attr("checked","true"); 
3.在子窗口中调用父窗口中的另一个子窗口的方法(FRAME): 
parent.frames["Main"].Fun(); 
注意:建议使用[],这样比较兼容多个浏览器,()火狐/搜狗/谷歌不兼容。
posted @ 2014-09-03 21:31  红河小鱼  阅读(97)  评论(0编辑  收藏  举报