2012-02-21 68 views
7

我有這段代碼的問題:IE不支持「的insertBefore」

var logo = document.getElementById("move_this"); 
    prependElement('container', logo); 

    function prependElement(parentID, child) { 
     parent = document.getElementById(parentID); 
     parent.insertBefore(child, parent.childNodes[0]); 
    } 

在IE中我有一個錯誤:

SCRIPT438: Object doesn't support property or method 'insertBefore'

有沒有辦法解決這個問題?

+1

搜索,我發現這個http://stackoverflow.com/ questions/5172202/does-ie7-not-fully-support-javascripts-insertbefore-method – Alfabravo 2012-02-21 12:50:56

+2

哪個IE版本? – kapa 2012-02-21 12:51:01

回答

10

使用它這樣的:

var parent=document.getElementById(parentID); 

否則父母會是全球性的,但始終是一個全球性的父對象中,parent窗口(它是隻讀的)。

此外: IE需要作爲第二個參數的有效節點或無效,因此請確保父母擁有的childNodes避免發生錯誤:

parent.insertBefore(child,(parent.hasChildNodes()) 
          ? parent.childNodes[0] 
          : null); 
+4

'(parent.hasChildNodes())?parent.childNodes [0]:null'可以縮寫爲'parent.childNodes [0] || null' – KooiInc 2012-02-21 13:12:17

+0

這就是我工作得很好:)非常感謝你:) – Teq1 2012-02-21 13:42:29

4

insertBefore作品正確IE只要第二個參數是一個有效的DOM元素,或nulltypeof nullObject,因此是一個typeof DOM元素)。

對於Array,任何出界限索引(在本例中爲0,因爲children[]爲空)將返回undefined。 IE在以下情況下停止工作作爲第二PARAM變得undefined -

parent.insertBefore(child, parent.childNodes[0]) 
//parent.childNodes[INDEX] 
//where `INDEX` is greater than parent.childNodes.length 

所以,這種情況下,更好的方法將是

var refEl = parent.childNodes[INDEX] || null; 
parent.insertBefore(newRowHolderNode.childNodes[0], refEl);