我有以下HTML,我想在div容器(.container)中重复5次。
<div class="block">
<div class="name">Name</div>
<div class="content>Content</div>
</div>
我有以下对象字面值:
var main_content = {
"content_1": {
"name": "Joe",
"position": "Baker"
},
"content_2": {
"name": "Jane",
"position": "Waitress"
}
"content_3", etc
}
我想克隆顶部HTML,并且对于每个块,将名称和内容更改为其各自的对象文字项。所以我希望HTML的输出如下所示。我怎么能这样做?
<div class="block">
<div class="name">Joe</div>
<div class="position>Baker</div>
</div>
<div class="block">
<div class="name">Jane</div>
<div class="position>Waitress</div>
</div>
...
答案 0 :(得分:1)
使用jQuery这应该相对容易。这对你有用吗?
for(var i in main_content)
{
var name = main_content[i].name,
position = main_content[i].position,
template = $('<div class="block">\
<div class="name">'+name+'</div>\
<div class="position">'+position+'</div>\
</div>');
template.appendTo($('.container'));
}
请在此处查看正在运行的jsFiddle演示&gt; http://jsfiddle.net/jLPkS/
答案 1 :(得分:1)
不要在循环中附加到DOM:
var block, resultHtml = '';
for(block in main_content){
resultHtml += '<div class="block"><div class="name">' + main_content[block].name + '</div><div class="position">' + main_content[block].position + '</div></div>'
}
$('your-selector').append(resultHtml);