瀏覽器同源策略允許同源(協定、域名、埠相同)的父頁面與 iframe 互相存取 DOM。jQuery 只需將正確的 document 物件傳入選擇器上下文即可。
| 方向 | jQuery 寫法 | 說明 |
|---|---|---|
| 父頁 → iframe | $(window.frames['iframeName'].document) |
iframeName 為 iframe 的 name 或 id 屬性值 |
| iframe → 父頁 | $(window.parent.document) |
跨層級存取頂層父頁 |
// 假設 iframe 中有 ...
// 方式 1:.find() 鏈式
$(window.frames['iframeChild'].document).find('#child')
// 方式 2:選擇器上下文參數
$('#child', window.frames['iframeChild'].document)
// 兩者完全等價,選擇器上下文寫法更簡潔
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>父頁面</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<h2>父頁面控制面板</h2>
<button id="checkAllInFrame">全選 iframe 中的 Radio</button>
<button id="uncheckAllInFrame">取消全選</button>
<hr>
<iframe id="iframeChild" name="iframeChild" src="child.html" style="width:100%; height:300px; border:1px solid #ccc;"></iframe>
<script>
$('#checkAllInFrame').click(() => {
// 關鍵:等待 iframe 載入完成
const iframeDoc = window.frames['iframeChild'].document;
if (!iframeDoc || iframeDoc.readyState !== 'complete') {
alert('iframe 尚未載入完成');
return;
}
$(iframeDoc).find("input[type='radio']").prop('checked', true);
});
$('#uncheckAllInFrame').click(() => {
const iframeDoc = window.frames['iframeChild'].document;
$(iframeDoc).find("input[type='radio']").prop('checked', false);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>iframe 子頁面</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<h3>子頁面表單</h3>
<form>
<label><input type="radio" name="group1" value="a"> 選項 A</label><br>
<label><input type="radio" name="group1" value="b"> 選項 B</label><br>
<label><input type="radio" name="group1" value="c"> 選項 C</label><br><hr>
<label><input type="radio" name="group2" value="x"> 選項 X</label><br>
<label><input type="radio" name="group2" value="y"> 選項 Y</label><br>
</form>
<button id="checkParentRadios">反向操作:全選父頁面 Radio</button>
<script>
$('#checkParentRadios').click(() => {
// 存取父頁面 DOM
$(window.parent.document).find("input[type='radio']").prop('checked', true);
});
</script>
</body>
</html>
postMessage 通訊。iframeDoc.readyState === 'complete' 或監聽 iframe.onload。input[@type='radio'](XPath 語法),已棄用,請改用 input[type='radio']。.prop() vs .attr(): 設定勾選狀態請用 .prop('checked', true/false),.attr() 僅影響初始 HTML 屬性。/** 取得 iframe 的 jQuery 包裝 document
* @param {string} frameName - iframe 的 name 或 id
* @returns {jQuery|null} 可直接用 .find() 的 jQuery 物件,失敗回傳 null
*/
function $iframe(frameName) {
const frame = window.frames[frameName];
if (!frame) return console.warn(`iframe "${frameName}" not found`), null;
const doc = frame.document;
if (!doc || doc.readyState !== 'complete') return console.warn('iframe not ready'), null;
return $(doc);
}
// 使用範例
$iframe('iframeChild')?.find('#someId').addClass('highlight');
掌握這套雙向存取模式,即可輕鬆實作嵌入式編輯器、多步驟精靈表單、第三方元件整合等跨框架互動場景。