当前位置:Gxlcms > JavaScript > Jquery获取iframe的各级元素、内容或者ID的实例方法详解

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

时间:2021-07-01 10:21:17 帮助过:3人阅读

在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('koyoz').contentWindow.document.getElementById
('test').style.color='red'

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

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

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

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

以上就是Jquery获取iframe的各级元素、内容或者ID的实例方法详解 的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行