这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
这篇文章主要介绍了 js 判断 iframe 中元素是否存在的实现代码, 需要的朋友可以参考下
本文章来给大家介绍 js 判断 iframe 中元素是否存在代码,有需要了解的朋友可进入参考。
一、纯原生态 js 实现方法, 代码如下:
- <script>
- var bb = document.getElementById('PreviewArea').contentWindow.document.getElementById('aPic');
- if( bb )
- {
- }
- else
- {
- }
- //apic为子页面Preview.aspx里面元素的Id
- </script>
- <body>
- <iframe name="PreviewArea" id="PreviewArea" scrolling="yes" width="100%" height="290" frameborder="1" src="Preview.aspx"></iframe>
- </body>
二、现在流行的 jquery 实现方法, 代码如下:
- if($(window.frames["iframepage"].document).find('.l-grid-row-cell').length > 0){
- alert(1);
- }else{
- alert(2);
- }
以上代码,判断 id 为 iframepage 的 iframe 中 CSS 为 1-grid-row-cell 的元素是否存在。 附
Jquery 取得 iframe 中元素的几种方法 在 iframe 子页面获取父页面元素
- $('#objId', parent.document);
- // 搞定...
- 在父页面 获取iframe子页面的元素
- $("#objid",document.frames('iframename').document)
- $(document.getElementById('iframeId').contentWindow.document.body).html()
显示 iframe 中 body 元素的内容
- $("#testId", document.frames("iframename").document).html();
- 根据iframename取得其中ID为"testId"元素
- $(window.frames["iframeName"].document).find("#testId").html()
2、用 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.phperz.com
- </div>
- </body>
- </html>
1. 在 index.html 执行 JS 直接访问: document.getElementById('koyoz').contentWindow.document.getElementById('test').style.color='red' 通过在 index.html 访问 ID 名为'koyoz'的 iframe 页面, 并取得此 iframe 页面内的 ID 为'test'的对象, 并将其颜色设置为红色. 此代码已经测试通过, 能支持 IE/firefox。 2. 在 index.html 里面借助 jQuery 访问:
$("#koyoz").contents().find("#test").css('color','red');
此代码的效果和 JS 直接访问是一样的, 由于借助于 jQuery 框架, 代码就更短了. 另外,有网友提供了如下的示例: 用 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")
来源: http://www.phperz.com/article/17/0517/329200.html