我有一个json数据对象,我用$。each tod tomy以动态检索数据,我想做的是显示除一个值之外的所有值,我不喜欢希望将ID显示在HTML结构中。我该怎么做?谢谢你
这是我的JSON数据对象:
$arrData['firstInfo'] = array('title'=> 'Cars');
$arrData['secondInfo'] = array('id', 'reference', 'size','name');
$arrData['thirdInfo'] = array(array('1', 'Ref12012', 'big', 'Toyota'),
array('2', 'Ref16489', 'small', 'Peugeot'),
array('3', 'Ref56479', 'medium', 'Mercedes')
);
这是我的代码:
Html += '<div>';
$.each(arrData['secondInfo'], function(Idx, currentValue)
{
Html += '<div>'+ currentValue +'</div>';
});
Html += '</div>';
$.each(arrData['thirdInfo'], function(Idx, currentValue){
Html += '<div>';
// columns
$.each(currentValue, function(Idx, currentValueCol){
Html += '<div>'+ currentValueCol +'</div>';
});
Html += '</div>';
});
您可以通过保留" ID"字段的索引并在最后一个循环中使用它来实现这一目标。在以下小提琴上,indexOfIdField
保留数据。
var arrData = {"firstInfo":{"title":"Cars"},"secondInfo":["id","reference","size","name"],"thirdInfo":[["1","Ref12012","big","Toyota"],["2","Ref16489","small","Peugeot"],["3","Ref56479","medium","Mercedes"]]};
var Html = '';
Html += '<div>';
var indexOfIdField = -1;
$.each(arrData['secondInfo'], function(Idx, currentValue)
{
if(currentValue == 'id'){
indexOfIdField = Idx;
}else{
Html += '<div>'+ currentValue +'</div>';
}
});
Html += '</div>';
$.each(arrData['thirdInfo'], function(Idx, currentValue){
Html += '<div>';
// columns
$.each(currentValue, function(Idx, currentValueCol){
if(indexOfIdField != Idx){
Html += '<div>' + currentValueCol +'</div>';
}
});
Html += '</div>';
});
$('#content').html(Html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div>
我建议您以不同的方式定义数据阵列。在这个 方式,您可以在循环时使用字段名称(IDX变量)。
$arrData['firstInfo'] = array('title'=> 'Cars');
$arrData['dataList'] = [
[
'id' => 1,
'reference' => 'Ref12012',
'size' => 'big',
'name' => 'Toyota'
],
[
'id' => 2,
'reference' => 'Ref16489',
'size' => 'small',
'name' => 'Toyota'
],
[
'id' => 3,
'reference' => 'Ref56479',
'size' => 'medium',
'name' => 'Toyota'
]
];
我找到了一种简单的方法,可以通过添加此
来跳过环路迭代的第一行function(i) {
if (i > 0)
DoStuff();
}