A-A+

jQuery判断iframe中元素是否存在的方法

2016年01月07日 前端设计 暂无评论 阅读 5 views 次

jQuery判断iframe中元素是否存在的方法比较简单只要判断框架window.frames["iframepage"]指定值是不是存在就可以了,下面整理了一些例子大家可进入参考.

例子,代码如下:

  1. if($(window.frames["iframepage"].document).find('.l-grid-row-cell').length > 0){  
  2.   alert(1);  
  3. }else{  
  4.   alert(2);  
  5. }  

以上代码,判断id为iframepage的iframe中css为1-grid-row-cell的元素是否存在,附,Jquery取得iframe中元素的几种方法.

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

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

在父页面 获取iframe子页面的元素

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

显示iframe中body元素的内容,代码如下:

  1. $("#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:

代码如下:

  1.  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
  2. <html xmlns="http://www.w3.org/1999/xhtml">   
  3. <head>   
  4. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />   
  5. <title>页面首页</title>   
  6. </head>   
  7. <body>   
  8. <iframe src="iframe.html" id="koyoz" height="0" width="0"></iframe>   
  9. </body>   
  10. </html>  

iframe.html 内容,代码如下:

  1.  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
  2. <html xmlns="http://www.w3.org/1999/xhtml">   
  3. <head>   
  4. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />   
  5. <title>iframe.html</title>   
  6. </head>  
  7. <body>   
  8. <div id="test">www.xiariboke.net</div>   
  9. </body>   
  10. </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")

标签:

给我留言