DIV CSS 佈局教程網

在 jQuery 中獲取與操作 iframe 內外元素
編輯:JQuery特效代碼     

iframe 的操作一直是前端裡容易翻車的環節,因為它牽涉到兩份 document 與同源政策。先把原生寫法記清楚,再套上 jQuery 就簡單了。

原生 DOM 寫法

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

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

加上 jQuery 選擇符

做法就是在原生寫法外面包一層 $():

// 父視窗中操作 iframe
$(window.frames["iframeChild"].document)

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

取得 iframe 內的 DOM 元素

// 方法一:先包成 jQuery 物件再 find
$(window.frames["iframeChild"].document).find("#child")

// 方法二:把 document 當作第二個參數傳入
$("#child", window.frames["iframeChild"].document)

實戰範例

// 1. 在父視窗中,選中 iframe 內的所有單選按鈕
$(window.frames["iframeChild"].document).find("input[@type='radio']").attr("checked", "true");

// 2. 在 iframe 內,選中父視窗中的所有單選按鈕
$(window.parent.document).find("input[@type='radio']").attr("checked", "true");

兩個容易踩到的坑

第一,屬性選擇器不要寫 @。範例中的 input[@type='radio'] 是 jQuery 1.2 時代的舊語法,1.3 之後已移除,正確寫法是 input[type='radio']。

第二,同源政策無法繞過。若 iframe 指向不同網域,存取其 document 會直接拋出安全性錯誤,這不是語法問題而是瀏覽器的硬性限制。跨域的 iframe 只能透過 postMessage 溝通。

另外,設定 checked 建議用 .prop("checked", true) 而非 .attr();在 jQuery 1.6 之後,checked、selected、disabled 這類「目前狀態」屬性的正確操作方式是 prop。

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