[英]Generate Anchor Links based on ID (JSON, jQuery)
我正在嘗試根據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中進行分配來實現此目的?
這不是您的方式:
$("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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.