jquery、js調用iframe父視窗與子視窗元素的方法整理

來源:互聯網
上載者:User

標籤:方法   alt   tools   body   copyto   attr   type   idt   head   

1. jquery 在iframe子頁面擷取父頁面元素代碼如下:

$("#objid", parent.document)

2. jquery在父頁面 擷取iframe子頁面的元素

代碼如下:

$("#objid",document.frames(‘iframename‘).document)

3.js 在iframe子頁面擷取父頁面元素代碼如下:

indow.parent.document.getElementByIdx_x("元素id");

4.js 在父頁面擷取iframe子頁面元素代碼如下:

window.frames["iframe_ID"].document.getElementByIdx_x("元素id");

5.子類iframe內調用父類函數:

window.parent.func();

 

 

用原生js在父頁面擷取iframe子頁面的元素,以及在子頁面擷取父頁面元素,這是平時經常會用到的方法,這裡寫一個例子來總結下:

1、父頁面(demo.html),在父頁面修改子頁面div的背景色為灰色,原來為紅色:

[html] view plain copy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5.     <title>demo首頁面</title>  
  6.     <script type="text/javascript">  
  7.     window.onload = function(){  
  8.         var _iframe = document.getElementById(‘iframeId‘).contentWindow;  
  9.         var _div =_iframe.document.getElementById(‘objId‘);  
  10.         _div.style.backgroundColor = ‘#ccc‘;  
  11.     }  
  12.       
  13.     </script>  
  14. </head>  
  15.   
  16. <body>  
  17.   
  18. <div id=‘parDiv‘>父頁面</div>  
  19. <iframe src="demo-iframe.html" id="iframeId" height="150" width="150"></iframe>    
  20. </body>  
  21. </html>  


2、子頁面(demo-iframe.html),在子頁面修改父頁面div的字型顏色為紅色,原來為黑色:

[html] view plain copy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5.     <title>子頁面demo13-iframe.html</title>  
  6.     <script type="text/javascript">  
  7.     window.onload = function(){  
  8.         var _iframe = window.parent;  
  9.         var _div =_iframe.document.getElementById(‘parDiv‘);  
  10.         _div.style.color = ‘red‘;  
  11.     }  
  12.     </script>  
  13. </head>  
  14.   
  15. <body>  
  16.     <div id=‘objId‘ style=‘width:100px;height:100px;background-color:red;‘>子頁面</div>  
  17. </body>  
  18. </html>  


3、:

(1)沒有加入js時的:


(2)加入js後的:

jquery、js調用iframe父視窗與子視窗元素的方法整理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.