我想要做的是分解从JSON文件中获取的内容。例如说我的JSON数据如下所示:
{
"paintings": {
"painting": [
{
"title": "Boardwalk 5",
"artist": "Arnie Palmer",
"image": "ap1.jpg",
"price": 850
},
{
"title": "A Lasting Piece",
"artist": "Arnie Palmer",
"image": "ap2.jpg",
"price": 450
},
{
"title": "Surf at High Tide",
"artist": "Arnie Palmer",
"image": "ap3.jpg",
"price": 950
},
{
"title": "The Games We Play",
"artist": "Arnie Palmer",
"image": "ap4.jpg",
"price": 850
}
]
}
}
我想将其附加到<div class="area1">
JSON数组中的前2个项目,然后将3和4附加到<div class="area2">
。这是我提取所有数据的方式:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'data.json',
dataType: 'json',
success: jsonParser
});
});
function jsonParser(json) {
$('#load').fadeOut();
$.getJSON('data.json', function(data){
$.each(data.paintings.painting, function(k,v){
var title = v.title;
var img = v.image;
var price = v.price;
///here is where I need help
$('.area1').append('<div class="painting"><img src="images/' + img + '" width="200" height="225" alt="' + title + '" /><br/><div class="title">' + title + '<br/>$' + price + '</div></div>')
});
});
}
这是我的HTML:
<body>
<div class="area1">...first half of JSON data here... </div>
<div class="area2">... second half of JSON data here </div>
</body>
因此,一个JSON文件的数据被分解,然后附加到两个区域
比@Rhumborls解决方案更详细。
$.getJSON('data.json', function(data) {
$.each(data.paintings.painting, function(k, v) {
var title = v.title;
var img = v.image;
var price = v.price;
var areaid;
switch (k) {
case 0:
case 1:
areaid = '.area1';
break;
case 2:
case 3:
areaid = '.area2';
break;
}
$(areaid).append('<div class="painting"><img src="images/' + img + '" width="200" height="225" alt="' + title + '" /><br/><div class="title">' + title + '<br/>$' + price + '</div></div>')
});
});
甚至更具可扩展性
$.getJSON('data.json', function(data) {
$.each(data.paintings.painting, function(k, v) {
var title = v.title;
var img = v.image;
var price = v.price;
// We figure out the area to append to by rounding down to nearest 10 and plus by 1
// key of 0-9 becomes 1, key of 10-19 becomes 2 i.e.
var areaid = '.area' + (Math.round(k / 10) + 1);
$(areaid).append('<div class="painting"><img src="images/' + img + '" width="200" height="225" alt="' + title + '" /><br/><div class="title">' + title + '<br/>$' + price + '</div></div>')
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句