如何将json对象的值添加到现有无序列表的span标记中(按正确顺序)?
试过这个,但它只是将对象的最后一个值添加到span标记:
$.each(case_data['stage'+id+''], function(key, value) {
$('#stageInfo li').each(function() {
$(this).find('span').text(value);
});
});
对象
{
"baseline":{
"duration":"1 year",
"age":"45",
"hba1c":"7.6",
"fpg":"7.9",
"bmi":"29",
"complications":"Overweight Hypertension",
"baseline":"Metformin"
},
"stage1":{
"duration":"2 years",
"age":"46",
"hba1c":"8.1",
"fpg":"8.3",
"bmi":"29",
"complications":"Limited Progression Hypertension",
"baseline":"Metformin"
},
"stage2":{
"duration":"5 years",
"age":"49",
"hba1c":"8.2",
"fpg":"8.4",
"bmi":"33",
"complications":"Patient takes early retirement; daily physical activity reduced",
"baseline":"Metformin"
},
"stage3":{
"duration":"10 years",
"age":"55",
"hba1c":"9.3",
"fpg":"9.8",
"bmi":"33",
"complications":"Diagnosed with retinopathy grade 2",
"baseline":"Metformin"
}
}
HTML
<ul id="stageInfo" class="stage_info">
<li>1 <span></span></li>
<li>2 <span></span></li>
<li>3 <span></span></li>
<li>4 <span></span></li>
<li>5 <span></span></li>
<li>6 <span></span></li>
<li>7 <span></span></li>
</ul>
答案 0 :(得分:1)
就像那样:http://jsfiddle.net/hyUzd/
var ind = 0;
$.each(case_data['stage'+id], function(key, value) {
$('#stageInfo li').eq(ind++).find('span').text(value);
});
答案 1 :(得分:1)
我会使用jQuery代码渲染li项目。
从UL中删除内容:
<ul id="stageInfo" class="stage_info"></ul>
并在循环中构建它:
var index = 0;
$.each(case_data['stage'+id+''], function(key, value) {
index++;
$("#stageInfo").append("<li>"+index+"<span>"+value+"</span></li>");
});
祝你好运