首先,没有正确的方法。
你这样做很好。
也就是说,我不得不用JavaScript创建很多次内容,所以我想出了一个生成内容的函数。它可以很容易地修改,我发现它保持代码,imo,更干净。在function createElement(element, attributes, text) {
// function to create an element with class and text if wanted.
// attributes is an object of key value items. Key is the attribute, value is the value.
// you could change the "class" to an argument and use it to set anyAttribute
var el = document.createElement(element);
$.each(attributes, function(key, value) {
el.setAttribute(key, value);
});
if (text) {
var t = document.createTextNode(text);
el.appendChild(t);
}
return el;
}
举个例子,可以这样称呼:
^{pr2}$
这将创建以下元素
您仍然需要用JavaScript构建元素并将它们附加到DOM中,这需要一些工作,但我发现它有助于DRY。在
另一方面,你可以像@或Duan所说的那样,使用前端框架,或者使用前端模板引擎。
框架通常在中包含模板引擎和数据绑定值,以便它们在值更改时发生更改,但您可以自己执行逻辑,只需在框架外部使用模板引擎。
根据您的需要,有多种模板引擎-https://garann.github.io/template-chooser/