我觉得我的方法不可读,而且从 JSON 对象生成项目列表并将其添加到现有 div 中看起来很丑。
我的html:
<ul id='to-be-filled'> </ul>
我的 JavaScript
myJson = [
{
"title": "First",
"action": "1st"
},
{
"title": "Second",
"action": "2nd"
},
{
"title": "Third",
"action": "3rd"
}
]
function genList(){
var outputList = '';
$.each(myJson, function() {
outputList += '<li>' + this.title + ': ' + this.action + '</li>'
});
$('#to-be-filled').html(outputList); //set the generated html string.
}
$(document).ready(function() {
genList(); //init
});
结果在这里:http://jsfiddle.net/GxdA6/
如何改善附加 html 字符串的困惑,尤其是我的真实代码具有更复杂的 DOM 和 JSON 数据结构?
最佳答案
如果您需要在客户端执行大量操作,我会考虑使用 templates 。该插件目前处于测试阶段,因此可能会发生变化,但我认为它的基础知识已经设置得很好。或者您可以使用另一个 jQuery 模板插件,有几个。我的主要信息不是“使用 jQuery 模板”,而是“使用模板”。 :-)
但是这个特定的插件正在出现,并且背后有一些强大的力量。您可以通过两种不同的方式定义模板:将其作为 script
元素包含在文档中:
<script id="your-li-template" type="text/x-jquery-tmpl">
<li>${title}: ${action}</li>
</script>
...然后您可以像这样检索和使用它:
var t = $("#your-li-template");
var outputList = t.tmpl(myJson);
或者您可以在 JavaScript 代码中将其定义为字符串,然后稍微不同地使用它(我怀疑这种差异是它仍处于测试阶段的部分原因):
// Compile it once
var t = $.template("<li>${title}: ${action}</li>");
// Use it as often as you need
var outputList = $.tmpl(t, myJson);
在这两种情况下,显然(从示例中)如果您给它一个数组,它会根据模板重复评估数组中的每个项目,因此您甚至不必循环。
关于javascript - 通过 Jquery 生成 HTML 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6681069/