Pat*_*cow 8 javascript each jquery json mustache
我有一些json对象,其中一些在其中有一些其他对象.
如果我只留下没有其他obj的json obj然后应用模板,一切顺利,我得到,在这种情况下3 li元素.
但如果我抓住原来的json obj,结果有点连线.我相信我需要做一个each
声明来迭代每个主json内部的每个子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",
}
Run Code Online (Sandbox Code Playgroud)
而我正在努力做到这样的事:尼克
测试
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;
}
Run Code Online (Sandbox Code Playgroud)
然后我只是将其附加到主ul.
谢谢
Jos*_*eph 26
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",
}]
Run Code Online (Sandbox Code Playgroud)
就是胡子模板中的这个:
{{#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}}
Run Code Online (Sandbox Code Playgroud)