我有一个包含来自json的数据的电话数组:
var phones = [
{
"age": 0,
"id": "motorola-xoom-with-wi-fi",
"imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
"name": "Motorola XOOM\u2122 with Wi-Fi",
"snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
},
我编写代码将该数组显示为列表ul li:
function createList_Task_4(){
$.each(phones, function(i, phone){
phones.push("<li>" + phone.age +"</li><br><li>" + phone.id +
"</li><br><img src='" + phone.imageUrl + "'/></li><br><li>" + phone.name + "</li><br><li>" + phone.snippet +"</li>" );
});
$('#phonesList').append(phones.join(''));
}
它显示我想要的数据,但在列表的顶部显示:
[object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object]
<ul>
<li>0</li>
<li>motorola-xoom-with-wi-fi</li>
<ul/>
如何删除此[object Object]
?
答案 0 :(得分:2)
问题是您的phone
数组已包含对象列表,您正在将html添加到现有元素集中。
因此,当您说phone.join()时,对象将呈现为[Object object]
。
您可以使用.map()(例如
)从源phone
创建一个新数组
function createList_Task_4() {
var array = $.map(phones, function (phone, i) {
return "<li>" + phone.age + "</li><li>" + phone.id +
"</li><br><img src='" + phone.imageUrl + "'/></li><li>" + phone.name + "</li><li>" + phone.snippet + "</li>";
});
$('#phonesList').append(array.join(''));
}
答案 1 :(得分:2)
原因是你正在推送已经有JSON对象的同一个数组phone
。而是使用新阵列。
var arr = [];
function createList_Task_4(){
$.each(phones, function(i, phone){
arr.push("<li>" + phone.age +"</li><br><li>" + phone.id +
"</li><br><img src='" + phone.imageUrl + "'/></li><br><li>" + phone.name + "</li><br><li>" + phone.snippet +"</li>" );
});
$('#phonesList').append(arr.join(''));
答案 2 :(得分:2)
每次迭代时将每个html直接附加到UL。如下
function createList_Task_4(){
$.each(phones, function(i, phone){
$('ul#phonesList').append("<li>" + phone.age +"</li><br><li>" + phone.id +
"</li><br><img src='" + phone.imageUrl + "'/></li><br><li>" + phone.name + "</li><br><li>" + phone.snippet +"</li>" );
});}