0

我有一个 Html 列表,我从 REST 调用接收数据作为 JSON 字典,我遍历并获取它们的值。但我找不到如何使用循环中的项目生成下面的 Html。

<div class="container">
<ul role="list">
    <li class="infoBasic" role="listitem">
        <div class="date">20-12-2012</div>
        <div class="ammount">-&euro;4,25</div>
    </li>
    <li class="infoDetails" role="listitem">
        <div class="place">data</div>
        <div class="category">data</div>
        <div class="description_title">data</div>
        <div class="description">data</div>
    </li>

   //repeat this for multi items received from REST

</ul>

$.ajax
  ({

   success: function (data){                    
        var transactions=data['transactions'];      

        $.each( transactions, function( key, value ) {
             $.each( value, function( key, value) {

                //here how to set/create the appropriate div elements(like above) 
                // with the values I get here in a loop? 

             });                        
      }); 

编辑下面的一些解决方案很好,但我不想要我的对象数组中的所有值,我怎样才能只将这些项目(日期、金额、地点..等)获取到 html div 并忽略字典中的其他项目

4

3 回答 3

1
$.each( value, function( key, value) {

            //here how to set/create the appropriate div elements(like above) 
            // with the values I get here in a loop? 

            $(".infoDetails").append("<div class='" + key + "'>" + value + "</div>");
         }); 
于 2013-01-09T17:23:38.847 回答
1

您可以使用..

     var data = "";

   $.each( transactions, function( key1, value1 ) {
         data +="<li class ='"+ key1 +"' role='listitem'>";

             $.each( value1, function( key, value) {
                 data +="<div class ='"+ key +"'>"+value+"</div>"; 
             });
     });  


   $("ul").html(data); // selecting ul element and then embedding html into it..
于 2013-01-09T17:29:49.840 回答
-1

试试这个......取一个变量说html......遍历json数组......在列表中添加项目......并将整个html放在一个div中......

var html='<ul>';
$.ajax
  ({

   success: function (data){                    
        var transactions=data['transactions'];      

        $.each( transactions, function( key, value ) {
             $.each( value, function( key, value) { 
                html+='<li class="'+key+'">'+value+'</li>';
             });                        
      });
       } 
 }); 
html+='</ul>';
$('#idofdiv').html(html);
于 2013-01-09T17:25:25.070 回答