DIV CSS 佈局教程網

用 jQuery 跨 iframe 取得 DOM 物件的兩種寫法
編輯:JavaScript綜合知識     

頁面中嵌了 iframe,父頁要控制子頁的元素(或反過來)時,關鍵是取得對方的 document 物件。有了它,後續就跟一般 DOM 操作一樣。

基本操作

// 父視窗中操作 iframe:假設 iframe 的 id 為 iframeChild
$(window.frames["iframeChild"].document)

// 子視窗中操作父視窗
$(window.parent.document)

取得 iframe 內 DOM 的兩種寫法

// 寫法一:先取 document,再 find
$(window.frames["iframeChild"].document).find("#child")

// 寫法二:把 document 作為第二個參數(context)
$("#child", window.frames["iframeChild"].document)

兩者結果相同。寫法二在 jQuery 中效率通常略好,因為它會在指定上下文中直接查詢,而不必先建立一個 jQuery 物件再串接 find。

實用範例

1. 在父視窗中選取 iframe 內的所有單選按鈕

$(window.frames["iframeChild"].document)
    .find("input[type='radio']")
    .prop("checked", true);

2. 在 iframe 中選取父視窗的所有單選按鈕

$(window.parent.document)
    .find("input[type='radio']")
    .prop("checked", true);

兩個實務上會踩到的問題

跨來源(cross-origin)限制。若 iframe 的網域、通訊協定或連接埠與父頁不同,瀏覽器的同源政策會直接禁止存取 contentDocument,並在 console 拋 SecurityError。這不是 jQuery 的限制,而是瀏覽器安全機制,無法繞過。跨來源溝通的正確做法是 window.postMessage():

// 父頁 → iframe
document.getElementById('iframeChild').contentWindow
    .postMessage({ type: 'selectAll' }, 'https://child.example.com');

// iframe 內接收
window.addEventListener('message', function(e) {
    if (e.origin !== 'https://parent.example.com') return;   // 務必驗證來源
    if (e.data && e.data.type === 'selectAll') {
        $("input[type='radio']").prop("checked", true);
    }
});

使用 postMessage 時一定要驗證 e.origin,否則任何網站都能對你的頁面發送指令。

選擇器語法已過時。範例中的 input[@type='radio'] 使用了 jQuery 1.3 之前/XML 風格的 @ 前綴,在 jQuery 1.3 之後已被移除,必須寫成 input[type='radio']。另外,設定勾選狀態應使用 .prop("checked", true) 而非 .attr("checked", "true")——jQuery 1.6 起兩者語意已明確區分,attr 改的是 HTML 初始屬性,prop 改的是目前的互動狀態。

iframe 尚未載入完成時取不到元素。若父頁在 iframe 的 load 事件之前就去查 DOM,會得到空集合。應改為監聽 $('#iframeChild').on('load', function(){ ... }),或使用 contentWindow.document.readyState 輪詢確認。

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