首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

jQuery 根據 iframe src 屬性精確獲取目標 iframe 對象

     編輯:程式設計綜合問答

頁面中存在多個 iframe,僅 src 屬性不同。需根據 src 值精確選中目標 iframe 並獲取其 contentWindow,而非依賴索引(如 parent.$(".mainFrame")[1])這種脆弱方式。

解決方案:屬性選擇器

// 匹配 src 以 "/toProduct" 結尾的 iframe
var targetIframe = parent.$("iframe[src$='/toProduct']");

// 獲取 contentWindow
if (targetIframe.length) {
    var win = targetIframe[0].contentWindow;
    // 操作 win ...
}

選擇器說明

  • [src$='value']:屬性以 value 結尾(最常用,忽略域名/參數差異)。
  • [src^='value']:屬性以 value 開頭。
  • [src*='value']:屬性包含 value 任意位置。
  • [src='exact']:精確匹配完整 URL。

完整示例:跨域安全訪問

function getIframeWindow(srcSuffix) {
    try {
        var $iframe = parent.$("iframe[src$='" + srcSuffix + "']");
        if ($iframe.length === 0) {
            console.warn("未找到 src 結尾為 " + srcSuffix + " 的 iframe");
            return null;
        }
        // 同源策略:僅同域下可訪問 contentWindow
        return $iframe[0].contentWindow;
    } catch (e) {
        console.error("跨域訪問被攔截或 iframe 不存在", e);
        return null;
    }
}

// 使用
var productWin = getIframeWindow('/toProduct');
if (productWin) productWin.refreshData();

注意事項

  • 同源策略:跨域 iframe 無法直接訪問 contentWindow,需使用 postMessage 通信。
  • 動態加載:若 iframe 為動態創建,確保在 onload 後再查找。
  • 多匹配:若多個 iframe 匹配同一後綴,[0] 取第一個,建議使用更具體的選擇器(如添加 id 或 class)。

使用屬性選擇器根據 src 定位 iframe,比索引方式更健壯、可維護,是多 iframe 頁面交互的標準做法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved