使用appendChild向HTML元素添加SVG元素-在IE9中失败

Adding SVG element to HTML element with appendChild - failing in IE9?

本文关键字:元素 IE9 失败 添加 appendChild HTML 使用 SVG      更新时间:2023-09-26

我正在通过原型Ajax请求加载一个SVG文件,向其中添加一个类和一个id,然后将其放入div中

onSuccess: function(response) { 
    var svgElement = response.responseXML.documentElement;
    svgElement.setAttribute("id", "someId");
    svgElement.setAttribute("class", "someClass");
    // At this point, everything is fine. I can verify that in IE9,
    // I have a valid svgElement and the id and class have been correctly set.
    var someDiv = $('someDiv');
    someDiv.appendChild(svgElement); // This fails in IE9, but works elsewhere!
    someDiv.insert(svgElement.xml); // This works in IE9, but fails elsewhere!
}

我只关心那些更好的浏览器——IE9是我在这里要担心的最低的浏览器。

有什么事吗?我暂时切换插入方法,这取决于我是否在IE中,但我想深入了解并以正确的方式修复它。

我绕过了"responseXML在不同的文档中"的问题,只需在所有情况下使用responseText:创建新的文档

onSuccess: function(response) { 
    var svgDoc;
    if (window.DOMParser) {
      var domParser = new DOMParser();
      svgDoc = domParser.parseFromString(response.responseText, "text/xml");
    } else {
      svgDoc = new ActiveXObject("Microsoft.XMLDOM");
      svgDoc.async = false;
      svgDoc.loadXML(response.responseText);
    }
    var svgElement = svgDoc.documentElement;
}

如果你问我,这比导入文档(以及所有相关问题)更容易、更干净。