2017-03-06 67 views
0

如何從其他框架訪問框架元素。對於防爆:從Javascript中的其他框架訪問框架元素

main.html中:

<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </head> 
    <frameset rows="33%,33%,*"> 
     <frame class="fra" src="frame1.html"/> 
     <frame class="fra" src="frame2.html"/> 
    </frameset> 
</html> 

frame1.html:

<html> 
    <HEAD> 
     <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS" /> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </HEAD> 
    <body> 
     <b><p id="para"> This is frame one.html </p></b> 
    </body> 
</html> 

frame2.html:

<html> 
    <HEAD> 
     <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS" /> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </HEAD> 
    <body> 
     <b><p id="para"> This is frame two.html </p></b> 
     <button id="but"> Get data </button> 
     <script> 
      $(document).ready(function(){ 
       $("#but").click(function(){ 
        alert(window.frames[0].document.getElementById('para')); 
       }); 
      }); 
     </script> 
    </body> 
</html> 

一旦按鈕從幀2點擊然後我需要獲取frame1中存在的「para」id元素的數據。所以,我試圖訪問下面顯示的 元素。但它沒有奏效。

window.frames[0].document.getElementById('para') 

它顯示的錯誤爲:

Uncaught TypeError: Cannot read property 'document' of undefined

所以,window.frames[0]本身不確定 。可任何一個可以幫助我解決這個問題?

+0

由於安全使用父母訪問父母然後其他框架的瀏覽器將阻止的行動, 看到這個[答案](http://stackoverflow.com/questions/25098021/securityerror-blocked-a-frame-with -origin-from-access-a-cross-origin-frame) –

+0

[SecurityError:Blocked a frame with origin from access from a cross-origin-frame](http://msdn.microsoft.com/zh-cn/library/system.aspx?displaylang=zh-cn&id=25098021/securityerror-阻塞的一幀與 - 原點從 - 訪問-A-跨來源幀) –

回答

1

您應該在您的iframe上放置id,例如「iframe1」和「iframe2」。

<frame class="fra" src="frame1.html" id="frame1" /> 
    <frame class="fra" src="frame2.html" id="frame2" /> 

然後:

$(window.parent.document).find("#iframe1").contents().find("#para") 

應該給你從iframe2在框架中的一個訪問元素ID爲 「段」。 $(window.parent.document)將允許您從iframe2返回到主文檔,然後查找iframe1,然後通過contents()將允許您進入iframe1,您將可以在其中找到「#iframe2」段「元素。