提问人:kk1957 提问时间:10/13/2011 更新时间:10/13/2011 访问量:1048
jQuery 对象作为函数的参数
jquery object as parameter to function
问:
这是我的jquery响应:
[
{ "depot":
{
"id": "D1",
"intersection": {
"first": "Markham",
"second": "Lawrence"
},
"address": {
"number": "25",
"street": "Cougar Court",
"city": "Scarborough",
"province": "ON",
"postal_code": "M1J"
}
},
"vehicle": [
{
"id": "V1",
"depot_id": "D1",
"model": "Ford Focus",
"price": "45",
"km_per_litre": "15",
"cargo_cu_m": "YES",
"category": "Compact car",
"image": "www.coolcarz.com"
}
,
{
"id": "V2",
"depot_id": "D1",
"model": "Honda Civic",
"price": "45",
"km_per_litre": "150",
"cargo_cu_m": "YES",
"category": "Compact car",
"image": "www.coolcarz.com"
}
,
{
"id": "V8",
"depot_id": "D1",
"model": "Pontiac Aztek",
"price": "10",
"km_per_litre": "6",
"cargo_cu_m": "YES",
"category": "SUV",
"image": "www.nocoolcarz.com"
}
,
{
"id": "V12",
"depot_id": "D1",
"model": "Chevrolet Impala",
"price": "45",
"km_per_litre": "12",
"cargo_cu_m": "YES",
"category": "Standard car",
"image": "www.coolcarz.com"
}
,
{
"id": "V29",
"depot_id": "D1",
"model": "Nissan Leaf",
"price": "150",
"km_per_litre": "0",
"cargo_cu_m": "YES",
"category": "Electronic Car",
"image": "www.coolcarz.com"
}
]
}
,
{ "depot":
{
"id": "A1",
"intersection": {
"first": "Markham",
"second": "Lawrence"
},
"address": {
"number": "25",
"street": "Cougar Court",
"city": "Scarborough",
"province": "ON",
"postal_code": "m1J"
}
},
"vehicle": [
]
}
]
我想做的是,在我的代码中的某个时刻,当我收到这个响应数据时,我想将 ,比如 data[0] 或 data[0].vehicle[1] 传递给一个函数 我现在的做法是:
function(data) {
var items = [];
for( i=0; i<data.length; i++){
items.push('<b>' + data[i].depot.intersection.first+"-"+ data[i].depot.intersection.second + " depot has following cars:"+ '</b>');
for( k=0; k<data[i].vehicle.length;k++){
str = '<li> <a href="#" onClick="moreInfo('+data+')">' + data[i].vehicle[k].category +"</a>, $"+ data[i].vehicle[k].price +' a day </li>';
items.push(str);
实际上,我正在尝试创建一个超链接(将车辆类别作为文本),当用户单击此超链接时,我想将车辆信息数组传递给一个名为moreInfo的新函数,该函数可以完成其工作。现在,当我执行此操作并单击超链接时,我看到错误
missing ] after element list
timepass([object Object],[object Object]
有什么想法吗?
答:
0赞
WooDzu
10/13/2011
#1
从 json 代码的开头和结尾删除 2 个方括号,并将其用作对象而不是数组。
您所做的是创建一个对象数组,而不是 JSON 对象
评论
0赞
Jordan Running
10/13/2011
这是不正确的。有效的 JSON 可以将对象 () 或数组 () 作为其最顶层的对象。请参阅RFC的开头:“JSON文本是序列化的对象或数组。{}
[]
JSON-text = object / array
"
0赞
WooDzu
10/13/2011
我并不是说这是不正确的,只是建议使用对象表示法而不是数组表示法。对不起,如果我让这个令人困惑
0赞
kk1957
10/14/2011
WooDzu,你能说得更具体一点吗?
0赞
WooDzu
10/14/2011
在 Json 表示法(或生成器的代码)中将所有方括号更改为圆括号,然后像只有一个区别一样遍历解析的对象,即使用 loop for(Depot in data)。对象中没有方法,因此您可以安全地使用它。
评论