」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用JavaScript訪問iframe內部的元素?

如何使用JavaScript訪問iframe內部的元素?

發佈於2025-03-23
瀏覽:575

How to Access Elements Inside an iFrame Using JavaScript? 
在您擁有包含文本area的iframe的網頁中,使用javaScript

訪問iframe Elements,您可能會遇到使用標準JavaScript Techniques訪問Textarea的值。通常,您將使用window.parent.getElementById()。值在父頁面中檢索值。但是,由於其隔離性質而導致的iframe失敗。

要解決此限制,需要一個動態解決方案,因為在運行時可能會更改IDS和名稱。關鍵在於訪問iframe內容而不依賴其ID或名稱。以下JavaScript代碼提供了一個全面的解決方案:

函數iframeref(frameref){ 返回Frameref.ContentWindow ? frameref.contentwindow.document :frameref.contentdocument } var Inside = iframeref(document.getElementById('one''))

此代碼獲取iframe參考,並動態標識iframe是使用contentwindow或contentDocument。 It then assigns the reference to the inside variable.

With the inside variable, you can now access the elements within the iFrame and, in this specific case, the textarea:

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

This comprehensive solution provides reliable access to elements inside iFrames, regardless of their runtime-changing IDs or名稱。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3