window.frames && iframe 跨頁面通信


1.定義

frames[]是窗口中所有命名的框架組成的數組。這個數組的每個元素都是一個Window對象,對應於窗口中的一個框架。

2.用法

假設iframe 是一個以存在的 iframe 的 ID 和 NAME 值,獲取iframe的方法有:

document.getElementById(“iframe”);  (獲取的是 iframe 元素,可改變iframe的 src 或者 border , scrolling 等 attributes)

window.frames[“iframe”];  //   window.frames[window.frames.length - 1]     (獲取的是window窗體,可通過其 document 屬性操作dom, 可使用iframe內的函數、變量)

例子:

$(window.frames["iframe"].document).find("#name").val("");

3. 擴展  iframe 跨頁面通信

parent.html

<html>

<head>
    <style>
        h1{
            color: #5dd;
        }
    </style>

</head>

<body>
    <h1>parent</h1>
    <input id="button" type="button" value="調用child.html中的函數say()" onclick="callChild()" />
    <iframe name="myFrame" id="iframea" src="child.html" onload="load()"></iframe>
    <script type="text/javascript">
        function say() {
            alert("parent.say");
        }

        function callChild() {
            myFrame.window.say();
            myFrame.window.document.getElementById("button").value = "parent調用結束";
        }
        function load(){
            // console.log(document.getElementById('iframea').contentDocument.getElementById('button'));
            console.log(document.getElementById('iframea').contentWindow.document.getElementById('button'));

        }
        

    </script>
</body>

</html>
View Code

 

 

child.html

<html>

<head>
    <style>
        body{
            background-color: #666;
        }
        h1{
            color:red;
        }
    </style>
</head>

<body>
    <h1>chlid</h1>
    <input id="button" type="button" value="調用parent.html中的say()函數" onclick="callParent()" />
    <script type="text/javascript">
        function say() {
            alert("child.say");
        }

        function callParent() {
            parent.say();
            parent.window.document.getElementById("button").value = "child調用結束";
        }
    </script>
</body>

</html>
View Code

 知識點:

window.parent 獲取上一級的window對象

window.top 獲取最頂級容器的window對象
window.self 返回自身window的引用

 

iframe.contentWindow, 獲取iframe的window對象 

iframe.contentDocument, 獲取iframe的document對象 

 

判斷iframe是否加載完成有兩種方法:

1. iframe上用onload事件
2. 用document.readyState=="complete"來判斷

 

js在iframe子頁面操作父頁面元素代碼:  window.parent.document.getElementByIdx_x("父頁面元素id");

在iframe中調用父頁面中定義的方法和變量:   window.parent.window.parentMethod();      window.parent.window.parentValue;

jquery在iframe子頁面獲取父頁面元素代碼如下:    $("#objid",parent.document)

 

js在父頁面獲取iframe子頁面元素代碼如下:     window.frames["iframe_ID"].document.getElementByIdx_x("子頁面元素id");

父頁面操作iframe子頁面的方法和變量      window.frames["iframe_ID"].window.childMethod();      window.frames["iframe_ID"].window.childValue;

jquery在父頁面獲取iframe子頁面的元素       $("#objid",document.frames('iframename').document)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM