我正在尝试根据JSON数据中的ID填充锚链接。 到目前为止,我有这个JSON数据。
{
"_meta": {
"status": "ok",
"api_version": 1,
"per_page": 20,
"current_page": 1,
"total_pages": 5,
"links": {
"next": "?page=2",
"previous": null
}
},
"data": [
{
"id": 1,
"name": "Andrew"
},
{
"id": 2,
"name": "Josh"
},
{
"id": 3,
"name": "John"
}
]
}
这是我的HTML代码。
<div id = "links"></div>
这是我的jQuery代码,用于获取ID并在Anchor上显示它们。
$.each(json.data, function(entryIndex, entry){
$("a.names").attr("href", "details?=" + entry.id);
$("#links").append('<a class = "names">View</a>');
console.log(entry.id);
});
我在这里尝试实现的是生成锚链接,在HTML上看起来像这样。
<a href = "details?=1">View</a>
<a href = "details?=2">View</a>
<a href = "details?=3">View</a>
相反,结果是,
<a href = "details?=3">View</a>
<a href = "details?=3">View</a>
<a href = "details?=3">View</a>
所以,我使用console.log调试,返回
1
2
3
如何通过获取JSON的ID并在Anchor Link中分配来实现这一目标?
答案 0 :(得分:0)
这不是你的方式:
$("a.names").attr("href", "details?=" + entry.id);
所以你需要做的是:
$("a.names").last().attr("href", "details?=" + entry.id);
上面将获取插入的最后一个。 这是一个肮脏的工作修复。
实际上,你必须这样做:
$.each(json.data, function(entryIndex, entry){
$("#links").append('<a class="names" href="details?=" + entry.id>View</a>');
console.log(entry.id);
});
<强>段强>
json = {
"_meta": {
"status": "ok",
"api_version": 1,
"per_page": 20,
"current_page": 1,
"total_pages": 5,
"links": {
"next": "?page=2",
"previous": null
}
},
"data": [
{
"id": 1,
"name": "Andrew"
},
{
"id": 2,
"name": "Josh"
},
{
"id": 3,
"name": "John"
}
]
}
$.each(json.data, function(entryIndex, entry){
$("#links").append('<a class="names" href="details?=" + entry.id>View</a>');
console.log(entry.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="links"></div>