嗨我有一个JSON对象("/satisfaction_ratings.json"):
{
"satisfaction_ratings": [{
"id": 217414761,
"updated_at": "2015-02-26T07:15:32Z",
"comment": "You are awesome!"
}, {
"id": 217419001,
"updated_at": "2015-02-28T17:45:39Z",
"comment": "You are great!"
}, {
"id": 220481332,
"updated_at": "2015-03-01T11:19:56Z",
"comment": "You are brilliant!"
}, {
"id": 218225121,
"updated_at": "2015-03-02T05:36:08Z",
"comment": "You are fantastic!"
}, {
"id": 228307861,
"updated_at": "2015-03-25T18:39:47Z",
"comment": "You are incredible!"
}],
"next_page": null,
"previous_page": null,
"count": 5
}
Run Code Online (Sandbox Code Playgroud)
...一些HTML:
<div id="feedback"></div>
Run Code Online (Sandbox Code Playgroud)
...和一些jQuery:
<script>
$.getJSON( "/satisfaction_ratings.json", function( data ) {
var items = [];
$.each(data.satisfaction_ratings, function() {
// console.log(this.comment);
items.push("<li>" + this.comment + "</li>");
});
$( "<ul/>", {
"class": "comments_list",
html: items.join( "" )
}).
appendTo( "#feedback" );
});
</script>
Run Code Online (Sandbox Code Playgroud)
在JSON对象中,我的注释按日期升序排序.我想以相反的顺序在我的页面上显示它们(以便最新的位于顶部).
我尝试过以下方法:
$.reverse().each(data.satisfaction_ratings, function() {...});
Object.keys(data.satisfaction_ratings).sort().reverse().forEach(function(){...});
Run Code Online (Sandbox Code Playgroud)
和各种其他方式.我只是不确定我是怎么做的,以便以相反的顺序迭代我的JSON对象.
在使用之前尝试反转阵列 each
$.each(data.satisfaction_ratings.reverse(), function() {
// console.log(this.comment);
items.push("<li>" + this.comment + "</li>");
});
Run Code Online (Sandbox Code Playgroud)
var json = {
"satisfaction_ratings": [{
"id": 217414761,
"updated_at": "2015-02-26T07:15:32Z",
"comment": "You are awesome!"
}, {
"id": 217419001,
"updated_at": "2015-02-28T17:45:39Z",
"comment": "You are great!"
}, {
"id": 220481332,
"updated_at": "2015-03-01T11:19:56Z",
"comment": "You are brilliant!"
}, {
"id": 218225121,
"updated_at": "2015-03-02T05:36:08Z",
"comment": "You are fantastic!"
}, {
"id": 228307861,
"updated_at": "2015-03-25T18:39:47Z",
"comment": "You are incredible!"
}],
"next_page": null,
"previous_page": null,
"count": 5
};
$.each(json.satisfaction_ratings.reverse(),function(){
$('ul').append('<li>' + this.comment + '</li>');
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1088 次 |
| 最近记录: |