後台系統常用 iframe 承載表單或彈窗,資料往往需要在父頁與子頁之間流動。以下整理兩個方向的取值方式。
$('#btnCancel', $('#PopFrame')[0].contentWindow.document)
寫法要點是第二個參數——把 iframe 的 document 當作查詢上下文傳入。這裡必須先用 [0] 取出原生 DOM 元素,才能取得 contentWindow。
$("#PopContainer", parent.document)
直接以 parent.document 作為上下文即可,比前者簡單。
網友提供的另一組解法,用 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#PopFrame').contents().find('#btnCancel') 用 jQuery 的 contents() 就能取得 iframe 文件,語意比 [0].contentWindow.document 清楚,也更短。總結一句:同域用 jQuery 直接跨,跨域就只能靠 postMessage。另外別忘了把老舊的 @ 選擇器與 attr 用法一併更新。