简体   繁体   English

解析嵌套的JSON并插入带有值的列表项

[英]Parse Nested JSON and insert list items with values

<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: 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: 给定此处的列表项和JSON响应,如何访问nest元素的每个keyframe_id并按如下方式插入href中:

<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/ http://jsfiddle.net/alnitak/46QDg/上的工作演示

Do use a more specific selector if you need to! 如果需要,请使用更具体的选择器!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM