萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 跨框架操作 DOM:父頁面與 iframe 雙向存取完整指南

核心概念

瀏覽器同源策略允許同源(協定、域名、埠相同)的父頁面與 iframe 互相存取 DOM。jQuery 只需將正確的 document 物件傳入選擇器上下文即可。

兩種基本存取模式

方向jQuery 寫法說明
父頁 → iframe $(window.frames['iframeName'].document) iframeName 為 iframe 的 name 或 id 屬性值
iframe → 父頁 $(window.parent.document) 跨層級存取頂層父頁

在取得 document 後,兩種等效的元素查找方式

// 假設 iframe 中有 
...
// 方式 1:.find() 鏈式 $(window.frames['iframeChild'].document).find('#child') // 方式 2:選擇器上下文參數 $('#child', window.frames['iframeChild'].document) // 兩者完全等價,選擇器上下文寫法更簡潔

實戰範例:父頁全選 iframe 中的 Radio

父頁面 (parent.html)

<!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>

子頁面 (child.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>

關鍵注意事項

  1. 同源限制: 跨域(不同域名/埠/協定)將拋出安全錯誤。跨域場景請使用 postMessage 通訊。
  2. 載入時機: 父頁操作 iframe 前,必須確認 iframeDoc.readyState === 'complete' 或監聽 iframe.onload。
  3. jQuery 版本: 1.x/2.x/3.x 皆支援上述寫法。舊版文獻常見 input[@type='radio'](XPath 語法),已棄用,請改用 input[type='radio']。
  4. .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');

掌握這套雙向存取模式,即可輕鬆實作嵌入式編輯器、多步驟精靈表單、第三方元件整合等跨框架互動場景。

copyright © 萬盛學電腦網 all rights reserved