我对这段代码有问题:
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:对象不支持属性或方法"insertBefore"
有办法解决这个问题吗?
这样使用它:
var parent=document.getElementById(parentID);
否则,父对象将是全局的,但始终有一个全局父对象,即parent窗口(它是只读的)。
此外:IE需要作为第二个参数的有效节点或null,因此请确保父节点具有子节点以避免错误:
parent.insertBefore(child,(parent.hasChildNodes())
? parent.childNodes[0]
: null);
insertBefore
在IE
中正常工作,只要第二个参数是有效的DOM元素或null
(typeof null
是Object
,typeof
也是DOM元素)。
对于Array
,任何越界索引(在本例中为0
,因为children[]
为空)都将返回undefined
。IE在以下情况下停止工作,因为第二个参数变为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);
如上所述,.insertBefore
仅适用于有效节点(显式ID或全局文档引用)。本地变量引用将失败:
parent.insertBefore(child, localref); //error
在IE中,我们可以使用.sourceIndex
属性来获取"marker"元素的当前全局索引,在该索引之前插入新的子元素。以下是IE的修复程序:
parent.insertBefore(child, document.all[localref.sourceIndex]);
如果您确切地知道要在父树中插入元素的位置,则不必使用.sourceIndex
属性。以下属性运行良好:
parent.insertBefore(child, parent.all[1]); //must be a child
parent.insertBefore(child, parent.children[2]); //any sane index
parent.insertBefore(child, parent.firstChild); //if at least one child exists
parent.insertBefore(child, parent.lastChild); //if at least one child exists
parent.insertBefore(child, localref.nextSibling]); //if not last child
parent.insertBefore(child, localref.previousSibling]); //if not first child