DIV CSS 佈局教程網

jQuery 跨 iframe 操作元素:父子頁面互相取值的寫法
編輯:JQuery特效代碼     

後台系統常用 iframe 承載表單或彈窗,資料往往需要在父頁與子頁之間流動。以下整理兩個方向的取值方式。

從父頁面選取 iframe 內的元素

$('#btnCancel', $('#PopFrame')[0].contentWindow.document)

寫法要點是第二個參數——把 iframe 的 document 當作查詢上下文傳入。這裡必須先用 [0] 取出原生 DOM 元素,才能取得 contentWindow。

從 iframe 頁面選取父頁面的元素

$("#PopContainer", parent.document)

直接以 parent.document 作為上下文即可,比前者簡單。

另一種寫法:DOM 與 jQuery 混用

網友提供的另一組解法,用 window.frames 定位 iframe:

<iframe src="test.html" id="iframe1" width="700" height="300" frameborder="0" scrolling="auto"></iframe>

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

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

此寫法在 IE7 中測試通過。

實務注意事項

  • 同源限制是硬門檻:以上所有寫法都要求父子頁面同域(协议、網域、連接埠皆相同)。跨域時唯一正解是 window.postMessage 訊息溝通。
  • 選擇器語法已過時:input[@type='radio'] 這種帶 @ 的寫法在 jQuery 1.3 之後被移除,現應寫為 input[type='radio']。同樣地,attr("checked", "true") 建議改用 .prop("checked", true),因為 checked 屬於「當前狀態」而非「初始屬性」。
  • 時機問題:若 iframe 尚未載入完成就嘗試存取其 document,會得到空集合。請在 iframe 的 load 事件之後再操作。
  • 可讀性更好的替代方案:$('iframe#PopFrame').contents().find('#btnCancel') 用 jQuery 的 contents() 就能取得 iframe 文件,語意比 [0].contentWindow.document 清楚,也更短。

總結一句:同域用 jQuery 直接跨,跨域就只能靠 postMessage。另外別忘了把老舊的 @ 選擇器與 attr 用法一併更新。

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