首页  >  文章  >  web前端  >  Jquery获取iframe的各级元素、内容或者ID的实例方法详解

Jquery获取iframe的各级元素、内容或者ID的实例方法详解

伊谢尔伦
伊谢尔伦原创
2017-06-19 13:19:142407浏览

在iframe子页面获取父页面元素
代码如下:

$('#objId', parent.document);
// 搞定...

在父页面 获取iframe子页面的元素
代码如下:

$("#objid",document.frames('iframename').document)
$(document.getElementById('iframeId').contentWindow.document.body).html()
$("#testId", document.frames("iframename").document).html();

根据iframename取得其中ID为"testId"元素

$(window.frames["iframeName"].document).find("#testId").html()

用JS或jQuery访问页面内的iframe,兼容IE/FF 
注意:框架内的页面是不能跨域的!

假设有两个页面,在相同域下.
index.html 文件内含有一个iframe:

<!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=gb2312" />  
<title>页面首页</title>  
</head>  
  
<body>  
<iframe src="iframe.html" id="koyoz" height="0" width="0"></iframe>  
</body>  
</html>

iframe.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=gb2312" />  
<title>iframe.html</title>  
</head>  
  
<body>  
<div id="test">www.koyoz.com</div>  
</body>  
</html>

1. 在index.html执行JS直接访问:
JavaScript代码

document.getElementById(&#39;koyoz&#39;).contentWindow.document.getElementById
(&#39;test&#39;).style.color=&#39;red&#39;

通过在index.html访问ID名为'koyoz'的iframe页面,并取得此iframe页面内的ID为'test'的对象,并将其颜色设置为红色.
此代码已经测试通过,能支持IE/firefox .

2. 在index.html里面借助jQuery访问:
JavaScript代码

$("#koyoz").contents().find("#test").css(&#39;color&#39;,&#39;red&#39;);

此代码的效果和JS直接访问是一样的,由于借助于jQuery框架,代码就更短了.

以上是Jquery获取iframe的各级元素、内容或者ID的实例方法详解 的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn