首页 > 解决方案 > 从字符串创建 SVG 元素并将其附加到 div 元素

问题描述

我想从像这样的字符串创建 SVG 元素

var svgStr = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow"/>';

然后使用 JavaScript 将其附加到现有的 HTML 元素。尝试了很多东西,但我似乎陷入了这个错误: https ://i.stack.imgur.com/0XUXF.png

我也试过这个,但没有让它工作:https ://jsfiddle.net/ramnathv/rkkpfvfz/

如果你能用一个六岁的孩子能理解的方式来解释,我一点也不介意^^

非常感谢任何帮助!

<html>
<body>

<h2>Boolean Network</h2>

<button type="button" onclick="appendSVG1()">Next</button>
<button type="button" onclick="appendSVG2('svgAnchor', svgStr)">Next2</button>

<div id="svgAnchor" value="3">

</div>

<script>
var parser = new DOMParser();
var svgStr = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow"/>';

function appendSVG1(){
    anchor = document.getElementById("svgAnchor");
    //nextState = parseInt(anchor.getAttribute("value")) + 1;
    //anchor.setAttribute("value", nextState);
    newSVG = parser.parseFromString(svgStr, "image/svg+xml");
    anchor.appendChild(document.adoptNode(newSVG.documentElement));
}

function appendSVG2(id, xml_string){
  var doc = new DOMParser().parseFromString(xml_string, 'application/xml');
  var el = document.getElementById(id)
  el.appendChild(el.ownerDocument.importNode(doc.documentElement, true))
}

</script> 
</body>
</html> ```


  

标签: javascripthtmlsvg

解决方案


我不知道如何使您一直在尝试的方法起作用,但是有一个更简单的方法:将所有内容放入innerHTML并让浏览器整理出细节。

<html>
    <body>

    <h2>Boolean Network</h2>

    <button type="button" onclick="appendSVG('svgAnchor', svgStr)">Next</button>

    <div id="svgAnchor" value="3">

    </div>

    <script>
    var svgStr = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow"/>';

    function appendSVG(id, xml_string){
      var el = document.getElementById(id)
      el.innerHTML = xml_string;
    }

    </script> 
    </body>
    </html>

正如 enxaneta 指出的那样,您缺少</svg>结束标记,这可能是您最初的问题。 innerHTML将浏览器置于完全“自动修复错误”模式,因此像缺少结束标记这样的简单错误会得到静默修复。


推荐阅读