<ul>
<li><a href="" class="edit">a list item</a></li>
<li><a href="" class="edit">a list item</a></li>
<li><a href="" class="edit">a list item</a></li>
<li><a href="" class="edit">a list item</a></li>
<li><a href="" class="edit">a list item</a></li>
<li><a href="" class="edit">a list item</a></li>
</ul>
JSON:
{
"status": "ok",
"collection": [
{
"snapshot_id": 5110,
"keyframe_id": 601
},
{
"snapshot_id": 5100,
"keyframe_id": 610
},
{
"snapshot_id": 5130,
"keyframe_id": 614
},
{
"snapshot_id": 5142,
"keyframe_id": 616
},
{
"snapshot_id": 5156,
"keyframe_id": 617
},
{
"snapshot_id": 5178,
"keyframe_id": 619
}
]
}
Given the list items here and the JSON response, how would one access each keyframe_id of the nest element and insert in the href as such:
<ul>
<li><a href="601" class="edit">a list item</a></li>
<li><a href="610" class="edit">a list item</a></li>
<li><a href="614" class="edit">a list item</a></li>
<li><a href="616" class="edit">a list item</a></li>
<li><a href="617" class="edit">a list item</a></li>
<li><a href="619" class="edit">a list item</a></li>
The very simple way:
var collection = json.collection;
for (var i = 0; i < collection.length; i++) {
$("ul > li:eq(" + i + ") > a").attr("href", collection[i].keyframe_id);
}
Or vice versa:
$("ul > li").each(function(i) {
$(this).children("a").attr("href", json.collection[i].keyframe_id);
});
This is probably the absolute simplest way:
$('ul a').attr('href', function(i) {
return json.collection[i].keyframe_id;
});
Working demo at http://jsfiddle.net/alnitak/46QDg/
Do use a more specific selector if you need to!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.