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

查看:152
本文介绍了在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中可以使用的任何内容类似于上面示例中的方法,还是我坚持使用 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解决方案是首选,但任何提供解决方案的lib指针都会受到赞赏。

推荐答案

您可以使用DOMParser来解析XML: https://developer.mozilla.org/en/Parsing_and_serializing_XML 您可以使用importNode将其添加到现有文档中:http s://developer.mozilla.org/en/DOM/document.importNode 以此类结果......

You can use DOMParser to parse XML: https://developer.mozilla.org/en/Parsing_and_serializing_XML you can then use importNode to get that into your existing document if you want: https://developer.mozilla.org/en/DOM/document.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天全站免登陆