下面是JSON对象:
{
'id' => 'itemGuitar',
'description' => 'Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.',
'price' => 5695.99,
'urls' => array('http://www.thewho.com/',
'http://en.wikipedia.org/wiki/Pete_Townshend')
}
下面是我的getJSON代码:
$.getJSON("getDetailsJSON.php?ImageID=" + escape(itemName), function (json) {
var info = "<p>id: " + json["id"] + "</p>" +
"<p>description: " + json["description"] + "</p>" +
"<p>price: $" + json["price"] + "</p>" +
"<p>urls:</p><ul>";
$.each(json["urls"], function (i) {
info += "<li><a href='" + this[i] + "'>" + this[i] + "</a></li>";
});
info += "</ul>";
$("#description").append(info);
});
具体来看:
$.each(json["urls"], function (i) {
info += "<li><a href='" + this[i] + "'>" + this[i] + "</a></li>";
});
我的问题是"urls“循环中的值是不正确的。我获取列表形式的https,一次只有一个字母,而不是每个包含完整地址的列表元素。
发布于 2018-12-05 04:11:23
从jQuery documentation for each
在数组的情况下,每次向回调传递数组索引和相应的数组值。(该值也可以通过
this
关键字进行访问,但是Javascript将始终将this
值包装为Object
,即使它是一个简单的字符串或数字值。)
因此,在您的代码中,i
是迭代中当前元素的索引,而this
是当前url。
$.each(json["urls"], function (i) {
info += "<li><a href='" + this + "'>" + this + "</a></li>";
});
或者更好的方法是显式地使用value参数
$.each(json["urls"], function (i, url) {
info += "<li><a href='" + url + "'>" + url + "</a></li>";
});
https://stackoverflow.com/questions/53620623
复制相似问题