DIV CSS 佈局教程網

jQuery 取得 iframe 內外元素與判斷存在的方法
編輯:JavaScript綜合知識     

用 jQuery 判斷 iframe 中的元素是否存在相當簡單,只要取得框架的 document 再往下找即可。以下整理幾種常用寫法。

判斷 iframe 內某元素是否存在

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

這段程式碼判斷 id 為 iframepage 的 iframe 中,是否存在 class 為 l-grid-row-cell 的元素。核心邏輯是「取到 iframe 的 document → 用 find 搜尋 → 檢查 length」,其中 length > 0 就是存在與否的判斷依據。

父子頁面互相取元素

在 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();  // 依 name 取得其中 id 為 testId 的元素
$(window.frames["iframeName"].document).find("#testId").html(); // 另一種寫法

跨瀏覽器存取 iframe(IE / Firefox)

重要前提:框架內的頁面不能跨網域,以下範例假設兩個頁面在同一個網域下。

index.html 內含一個 iframe:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://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" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://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.111cn.net</div>
</body>
</html>

做法一:用原生 JS 直接存取

document.getElementById('koyoz').contentWindow.document.getElementById('test').style.color = 'red';

這行程式在 index.html 中執行,取得 id 為 koyoz 的 iframe 頁面,再取其中 id 為 test 的元素,把顏色設為紅色。此寫法已測試可支援 IE 與 Firefox。

做法二:借助 jQuery

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

效果與原生 JS 相同,但因為有 jQuery 框架,程式碼短了很多。contents() 是這裡的關鍵方法,它能取得元素的所有子節點,包含 iframe 的 document。

在 iframe 中操作父視窗

用 jQuery 取得父視窗的某個元素時,需要 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");

幾點實務提醒

同源性是前提。只要 iframe 的 src 指向不同網域(或不同連接埠、不同通訊協定),瀏覽器就會拋出跨網域錯誤,上面所有寫法一律失效。跨域溝通的正確做法是 window.postMessage(),由子頁面 parent.postMessage(data, targetOrigin) 傳訊、父頁面監聽 message 事件接收,並務必在接收端驗證 event.origin。

用 attr 設定 checked 已過時。jQuery 1.6 之後應改用 .prop("checked", true),理由與前面討論過的一樣:checked 反映的是當前狀態,而 attr 讀的是 HTML 初始屬性。

iframe 未載入完成時取不到元素。若在 iframe 的內容還在載入中就執行查詢,會得到空集合。應該在 iframe 的 load 事件之後再操作:

$("#koyoz").on("load", function(){
    var $doc = $(this).contents();
    // 在這裡操作 $doc
});

modern 建議。除了跨域溝通之外,如今若只是為了在頁面中嵌入內容,<iframe> 的 sandbox 屬性與 loading="lazy" 值得善加利用;而若只是想隔離樣式,Shadow DOM 或元件化方案通常比 iframe 更好維護。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved