[英]Convert a HTML element in JS to be created using createElement()
I'm trying to convert a part of code I built, in JS to use more clean solutions.我正在尝试在 JS 中转换我构建的部分代码以使用更干净的解决方案。 I used to return HTML tags as follow:我曾经返回 HTML 标签如下:
return `<option value="${o.id}">${o.name}</option>`;
My goal is to use the create element or another way to write this differently to look cleaner.我的目标是使用 create 元素或其他方式以不同的方式编写它以看起来更干净。
this tag is a par of a map:这个标签是 map 的一个部分:
var selectOptions = response.map(o => {
return `<option value="${o.id}">${o.name}</option>`;
});
I would like to understand how to convert this doing like:我想了解如何将其转换为:
var x = document.createElement("option")
var value = "option value";
var text = "option.text"
And append
Or another way more useful in my example.或者在我的示例中更有用的另一种方式。
You can crate an Node
wrapper with document.createElement("div")
and attach the template String
created with node.innerHTML = template
;您可以使用document.createElement("div")
创建一个Node
包装器,并附加使用node.innerHTML = template
创建的template String
;
const createNodeFromTemplate = (template, wrapper, wrapperAttrs) => {
const node = document.createElement(wrapper);
for (const [key, value] of Object.entries(wrapperAttrs)) {
node.setAttribute(key, value);
}
node.innerHTML = template;
return node;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.