当使用.append时,jquery .each中的JSON数组仅显示数组的最后一个值

时间:2014-11-08 06:49:27

标签: javascript jquery arrays json



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Javascript Array Table</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<meta name="" content="">
</head>
<body>

<table>
     <thead>
          <tr>
               
               <th>Details</th>
               <th>Data</th>
               
           </tr>
     </thead>
     <tbody id="tbody"></tbody>
</table>


<script type="text/javascript">

//jQuery( document ).ready(function() {
function arrayprocess(){
		
		var display;
		
		var arrayobj = [{"name": "John","dept": "science","phone": "xxx-xxx-xxxx"}];
			
		jQuery.each(arrayobj, function(key, value){	
			
			jQuery.each(value, function(label, answer){
				display = '<tr><td>'+label+ '</td><td>' +answer+'</td></tr>'});


		});
		$('#tbody').append(display);
		

}
arrayprocess();
//});
</script>


</body>
</html>
&#13;
&#13;
&#13;

问题: 仅显示JSON only数组的最后一个值。前两个值的其余部分为name:Johndept:science ...

目前的输出:

详情数据

电话xxx-xxx-xxxx

预期输出

详情数据

姓名约翰

dept science

电话xxx-xxx-xxxx

1 个答案:

答案 0 :(得分:1)

你的append语句需要在每个函数内部,否则它只会附加最后一个结果,例如:

jQuery.each(arrayobj, function(key, value){ 

    jQuery.each(value, function(label, answer){
        display += '<tr><td>'+label+ '</td><td>' +answer+'</td></tr>';
    });
});