[英]Array in <ul><li> using JQuery
I have a phone array that contains data from json: 我有一个电话数组,其中包含来自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)."
},
I wrote code to display that array as list ul li: 我编写了代码以将该数组显示为列表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(''));
} }
It displays data as I'm want, but on top of the list it displays: 它根据需要显示数据,但在列表顶部显示:
[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/>
How to remove this [object Object]
? 如何删除这个
[object Object]
?
The problem is your phone
array already contains a list of objects, you are adding the html to the existing set of elements. 问题是您的
phone
阵列已经包含对象列表,您正在将html添加到现有的元素集中。
So when you say phone.join() the objects will be rendered as [Object object]
. 因此,当您说出phone.join()时,对象将呈现为
[Object object]
。
You can create a fresh array from the source phone
using .map() like 您可以使用.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(''));
}
The reason is you are pushing to the same array phone
which already have JSON objects inside. 原因是您要推送到已经具有JSON对象的同一台阵列
phone
。 Instead use a new array. 而是使用一个新的数组。
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(''));
Append each html directly to the UL every iteraction. 每次迭代将每个html直接附加到UL。 As below
如下
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>" );
});}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.