SVG/XML 中是否有一些innerHTML 替换? [英] Is there some innerHTML replacement in SVG/XML?

查看:29
本文介绍了SVG/XML 中是否有一些innerHTML 替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 HTML 中,我可以通过提供一个字符串形式的模板来构建一个简单的模板系统,替换它的某些部分,然后使用 innerHTML 将其分配给某个容器.

In HTML I can build a simple templating system by providing a template in form of a string, replace some parts of it and then assign it using innerHTML to some container.

var templ = '<span>{myText}</span>'
var newContent = templ.replace( '{myText}', someVariable );
document.querySelector( '#myContainer' ).innerHTML = newContent;

这样我就可以利用浏览器的 HTML 解析器,而不必重复使用 document.createElement().如果模板超出几个元素,后者可能会非常麻烦.

This way I can take advantage of the browser's HTML parser and do not have to repeatedly use document.createElement(). The later can be quite cumbersome, if the templates grows beyond a few elements.

然而,在 SVG 中,元素上没有像 innerHTML 甚至 innerSVG 这样的属性.

In SVG, however, there is no property on the elements as innerHTML or even innerSVG for that matter.

所以我的问题是:我可以在 SVG ro 中使用类似于上面示例中的方法的任何东西,还是我坚持使用 document.createElement()(或者分别是一些 lib使用它)?

So my question is: Is there anything I can use in SVG ro resemble the approach from the example above or am I stuck with document.createElement() (or respectivly some lib that uses it)?

和我的问题一样:Vanilla JavaScript 解决方案是首选,但任何指向提供解决方案的库的指针都值得赞赏.

推荐答案

您可以使用 DOMParser 解析 XML.如果你想通过 importNode 以这样的方式结束...

You can use DOMParser to parse XML. You can then use importNode to get that into your existing document if you want via importNode to end up with something like this...

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));

这篇关于SVG/XML 中是否有一些innerHTML 替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆