这是动态创建的以下表代码,我想获取存储在TD中的最后2个值。最后一个td值采用“键值对”的形式。我想显示如下内容:
<tbody>
{{#items}}
<tr>
<td>{{name}}</td>
<td>{{description}}</td>
<td id="newval">{{new_value}}</td>
<td id="oldval">{{old_value}}</td>
</tr>
{{/items}}
</tbody>
这是从服务器获取的json:
{
"result":"OK",
"items":[
{
"name":"abc",
"description":"desc",
"new_value":{
"description":"newvalue"
},
"old_value":{
"description":"oldvalue "
}
},
{
"name":"abc3",
"description":"desc2",
"new_value":{
"interval":"newvalue2"
},
"old_value":{
"interval":"oldvalue2 "
}
}
]
}
这是js:
$.each(lists,function(i,items){
for (var key in items) {
if(key == 'new_value'){
for(value in items[key]){
$("td#newval").html(value + " : " +items[key][value]);
}
}
}
});
同样,我正在为旧值进行操作,只是替换了“ td” id和值。但是发生的是,只有第一个td被更新为数组中“ new_value”的所有值,其余的td变为空白。我想以一种方式显示,它将遍历数组并找到与“ new_value”对象关联的键值对,并为相应的td呈现两个值。
<td>description: newvalue</td>
<td>interval: newvalue2</td>
我怎样才能做到这一点?谢谢!
由于元素的ID必须是唯一的,因此您应该使用其他属性来对元素进行分组。
这里一种可能的方法是使用类和数据属性来指定要映射到类似字段的属性
var data = {
"result": "OK",
"items": [{
"name": "abc",
"description": "desc",
"new_value": {
"description": "newvalue"
},
"old_value": {
"description": "oldvalue "
}
}, {
"name": "abc3",
"description": "desc2",
"new_value": {
"interval": "newvalue2"
},
"old_value": {
"interval": "oldvalue2 "
}
}]
};
var trmap = {};
$('table tr').each(function() {
trmap[$(this).children(':first-child').text().trim()] = this;
});
$.each(data.items, function(i, item) {
if (trmap[item.name]) {
var $tr = $(trmap[item.name]);
$tr.find('.val').text(function() {
var key = $(this).data('key');
var arr = [];
$.each(item[key], function(key, value) {
arr.push(key + ': ' + value)
});
return arr.join('');
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>abc</td>
<td>desc</td>
<td class="val" data-key="new_value">key: newvalue</td>
<td class="val" data-key="old_value">key: oldvalue</td>
</tr>
<tr>
<td>abc3</td>
<td>desc2</td>
<td class="val" data-key="new_value">key: newvalue2</td>
<td class="val" data-key="old_value">key: oldvalue2</td>
</tr>
</tbody>
</table>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句