如何通过js获取iframe框架中的内容

在父窗口中获取iframe中的元素

IE下:
格式:window.frames["iframe的name值"].document.getElementById("iframe中控件的ID").click(); 实例:window.frames["ifm"].document.getElementById("btnOk").click();
都支持的方法:
格式:document.getElementById("iframe的ID值").contentWindow.document.getElementsByName('radios');//IE firefox支持

 在iframe中获取父窗口的元素

Js代码

格式:window.parent.document.getElementById("父窗口的元素ID").click();  
实例:window.parent.document.getElementById("btnOk").click();  

jquery

在父窗口中获取iframe中的元素

格式:$("#iframe的ID").contents().find("#iframe中的控件ID").click();//jquery 方法1  
实例:$("#ifm").contents().find("#btnOk").click();//jquery 方法1  
格式:$("#iframe中的控件ID",document.frames("frame的name").document).click();//jquery 方法2  
实例:$("#btnOk",document.frames("ifm").document).click();//jquery 方法2  

在iframe中获取父窗口的元素

格式:$('#父窗口中的元素ID', parent.document).click();  
实例:$('#btnOk', parent.document).click();  

如果页面跨域,上面的方法都不行!

实例代码:index.html

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<p>当前框架</p>
<iframe src="if.html" width="300" height="300" id="currentif" name="currentif"></iframe>
</body>
</html>
<script language="javascript">
window.onload = function(){
   var sd =  window.top.document.getElementById("currentif").contentWindow;
//这里去掉前面的window.top也可以
var son = sd.document.getElementById("linkif"); son.onclick = function(){ alert("1"); }; }
//这里一定要放到onload下。如果直接写,可能导致元素获取失败!
</script>

 

实例代码:if.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<p id="linkif">嵌入的框架</p>
</body>
</html>

 

posted @ 2014-09-09 10:57  史洲宇  阅读(20099)  评论(0编辑  收藏  举报