document.getElementById('myframe')和window.frames[i]的區別

來源:互聯網
上載者:User

問題:使用window.frames[0].src怎麼都擷取不到url地址,而用$("#frame1").attr("src")卻可以

原因如下:

在DOM文件物件模型中,window對象處於最高層,而架構除了是當前表單的一個節點外,本身也是一個獨立window對象, 當frames作為window對象時,有name屬性,而沒有src屬性,只有作為節點時才有src屬性, 也就是說window.frames[0]這種寫法代表一個window對象,所以window.frames[0].src 當然是undefined了 ,這也是很多人容易混淆的原因。

若要獲得src屬性,可以這樣寫:document.getElementById(frame_id).src  //節點對象

<html>  <head>  <title>differences</title>  </head>  <body>      <iframe id="myframe" src="http://www.baidu.com" height=400 width=400></iframe>  </body>  <script type="text/javascript">document.body.onload = function(){//這種寫法沒問題//document.getElementById('myframe').src = 'http://www.google.com';//這種寫法會出錯//document.getElementById('myframe').location.href='http://www.google.com';//這種寫法可行//window.frames[0].location.href='http://www.google.com';//這種會有permission denied錯誤。//window.frames[0].src='http://www.google.com';}</script></html>

var obj = document.getElementById(“iframe”);//擷取對象

var dom = document.all.frames[“iframe”];//擷取DOM

一個是對象 一個是DOM.

如果只想改變iframe的 src 或者 border ,scrolling 等attributes(與property不是一個概念,property是不能寫在標籤內的,比如:scrollHeight,nnerHTML等),就需要用到第一種方法。

如果想取得iframe的頁面(不是iframe本身)。就需要使用第二種方法,因為它取得的是一個完整的DOM模型,比如想得到iframe的document.body的內容,就只能用第二種方法

另:document.getElementById取到的iframe是不能直接操作裡面的document的,只能這樣取:

在IE為是frames[id].document或document.getElementById(id).contentWindow.document; 

在firefox為frames[name].contentDocument或document.getElementById(id).contentDocument;做Iframe高度自適應的時候,一般用window.frames['frame'].getXXX()調用子頁面JS擷取高度,然後設定 document.getElementById('frame').style.height


轉載自:

http://www.cnblogs.com/daxian2012/archive/2012/08/03/2621564.html
http://bbs.csdn.net/topics/320021460#r_59704905

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.