Jquery取得iframe中元素的幾種方法Javascript Jquery擷取Iframe的元素、內容或者ID,反之也行!

來源:互聯網
上載者:User

query取得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()

 

用JS或jQuery訪問頁面內的iframe,相容IE/FF
注意:架構內的頁面是不能跨域的!

假設有兩個頁面,在相同域下.

index.html 檔案內含有一個iframe:

XML/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>頁面首頁</title> 
</head> 
 
<body> 
<iframe src="iframe.html" id="koyoz" height="0" width="0"></iframe> 
</body> 
</html>  
iframe.html 內容:

XML/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裡取得父視窗的某個元素的值
只好用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");

3.在子視窗中調用父視窗中的另一個子視窗的方法(FRAME):

  parent.frames["Main"].Fun();

  注意:建議使用[],這樣比較相容多個瀏覽器,() Firefox/搜狗/Google不相容。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.