【发布时间】:2017-07-11 09:03:31
【问题描述】:
有没有一种方法可以使用普通的旧 vanilla javascript(无框架)将 html 模板字符串转换为 Html 元素?
这是我尝试过的东西:
function renderBody(selector = body, template) {
const prop.text = 'foobar';
const templateString = `<div id='test'>${prop.text}</div>`
const test = document.createElement('div');
test.innerHTML = templateString;
document.querySelector(selector).appendChild(test);
}
这个实现有效,但它使用了 innerHTML 并添加了一个额外的包装 div。没有额外的div,有没有办法做到这一点?
【问题讨论】:
-
你为什么不直接 .appendChild(templateString) 并删除“测试”引用
-
或者只做
const test = document.createElement('div'); test.innerHTML = prop.text;不需要字符串插值... -
你确定
prop.text允许包含任意html吗?
标签: javascript html ecmascript-6