我一直在网上四处寻找,我很确定我已经知道答案(“否”),但我想检查一下:
IE 支持 importNode() 了吗?有没有比遍历 DOM 和创建节点更好的选择? (我见过 the clasic article by Anthony Holdener 但现在已经一年多了,我希望 IE 已经进化,或者有人有其他解决方法)
谢谢。
最佳答案
Internet Explorer 9 DOM API 中有一个函数 document.importNode()。但是IE9在调用时会抛出脚本错误
SCRIPT16386: No such interface supported
还需要定义源节点的命名空间(例如,当我们要导入 SVG - In IE9, Imported nodes do not seem to be recognized as SVG Elements )
Phrogz建议this有用的解决方法。但是,当我们导入具有特殊命名空间的元素(在 xmlns 属性中声明,例如 <svg xmlns="http://www.w3.org/2000/svg" …>…</svg>
)时,clone.setAttributeNS(a.namespaceURI,a.nodeName,a.nodeValue)
中会出现错误。因为属性 xmlns 的 namespaceURI 为空。
有适合我的解决方法:
var newNode;
try {
newNode = document.importNode(sourceDocumentElement, true);
}
catch(e) {
newNode = importNode(sourceDocumentElement, true);
}
function importNode(node, allChildren) {
switch (node.nodeType) {
case document.ELEMENT_NODE:
var newNode = document.createElementNS(node.namespaceURI, node.nodeName);
if(node.attributes && node.attributes.length > 0)
for(var i = 0, il = node.attributes.length; i < il; i++)
newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName));
if(allChildren && node.childNodes && node.childNodes.length > 0)
for(var i = 0, il = node.childNodes.length; i < il; i++)
newNode.appendChild(importNode(node.childNodes[i], allChildren));
return newNode;
break;
case document.TEXT_NODE:
case document.CDATA_SECTION_NODE:
case document.COMMENT_NODE:
return document.createTextNode(node.nodeValue);
break;
}
}
关于javascript - IE 支持 DOM importNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1811116/