javascript - 从字符串创建 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> ```
解决方案
我不知道如何使您一直在尝试的方法起作用,但是有一个更简单的方法:将所有内容放入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
将浏览器置于完全“自动修复错误”模式,因此像缺少结束标记这样的简单错误会得到静默修复。
推荐阅读
- mysql - 从 Json 数组中提取 JSON 对象到 mysql 8
- mysql - 使用 Golang 将数据从 kafka 保存到 mysql
- python - Python:设置下限和上限,将它们从数组中删除,并计算新数组的平均值
- yaml - YAML/YQ - 删除具有包含特定属性匹配的子部分的部分
- java - 如何在@ContextConfiguration(Java Spring)上替换@SpringBootTest?
- javascript - 我们不能在 DataTables 中同时移动两个表吗?
- javascript - What's the short circuiting way to rewrite for loop that breaks when condition is met?
- django-models - 如何运行迁移并添加电话号码
- python - 我无法理解这个点运算符
- javascript - 为什么写入后文件还没有填充?[NodeJS] [文件系统]