我有一些json对象,其中一些在其中有一些其他对象。
如果我只留下没有其他obj的json obj然后应用模板,一切顺利,我得到,在这种情况下3 li元素。
但如果我抓住原来的json obj,结果有点连线。我相信我需要做一个each
语句来迭代每个主要内部的每个子json obj
也许我有点困惑,所以这里有一些代码。
我有一些像这样的json数据:
{
"msg_id":"134",
"message":"Nick",
"comment":[
{
"com_id":"9",
"comment":"test",
},
{
"com_id":"10",
"comment":"testtt",
},
{
"com_id":"11",
"comment":"testtttt",
}]
},
{
"msg_id":"134",
"message":"Nick",
},
{
"msg_id":"134",
"message":"Nick",
}
我想尝试这样的事情: 缺口
测试
testtt
testtttt
缺口 缺口
我已经创建了这样一个模板:
function messagesTamplate(data)
{
$.each(data, function(index, obj)
{
msg += template.replace( /{{message}}/ig , obj.message );
if(obj.comment) {
$.each(obj.comment, function(key, val)
{
msg += template.replace( /{{comment}}/ig , val.comment );
});
}
});
return msg;
}
然后我只是将其附加到主ul。
感谢
答案 0 :(得分:27)
data
需要成为一个数组(请参阅随附的[]
)
var data = [{
"msg_id": "134",
"message": "Nick",
"comment": [{
"com_id": "9",
"comment": "test",
}, {
"com_id": "10",
"comment": "testtt",
}, {
"com_id": "11",
"comment": "testtttt",
}]
}, {
"msg_id": "134",
"message": "Nick",
}, {
"msg_id": "134",
"message": "Nick",
}]
就是胡子模板中的这个:
{{#data}} //loop through all data
{{message}} //pick out the "message" per iteration
{{#comment}} //loop through all comments in an iterated item
{{comment}} //pick out the comment
{{/comment}}
{{/data}}