在 HTML 中,我可以通过提供字符串形式的模板来构建一个简单的模板系统,替换其中的某些部分,然后使用innerHTML
到某个容器。
var templ = '<span>{myText}</span>'
var newContent = templ.replace( '{myText}', someVariable );
document.querySelector( '#myContainer' ).innerHTML = newContent;
这样我就可以利用浏览器的 HTML 解析器,而不必重复使用document.createElement()
。如果模板的数量超出了几个元素,后者可能会非常麻烦。
然而,在 SVG 中,元素没有属性,如innerHTML
甚至innerSVG
对于这个问题。
所以我的问题是:有什么我可以在 SVG 中使用的类似于上面示例中的方法还是我坚持使用document.createElement()
(或者分别使用它的一些库)?
As always with my questions: Vanilla JavaScript solutions are preferred, but any pointer to a lib providing a solution is appreciated.
您可以使用DOM解析器 https://developer.mozilla.org/en-US/docs/Web/API/DOMParser来解析 XML。然后,如果您愿意,可以使用 importNode 将其添加到现有文档中导入节点 https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode最终得到这样的事情......
var doc = new DOMParser().parseFromString(
'<svg xmlns="http://www.w3.org/2000/svg"><circle cx="100" cy="100" r="20"/></svg>',
'application/xml');
someElement.appendChild(
someElement.ownerDocument.importNode(doc.documentElement, true));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)