2017-06-17 53 views
1

Iam使用ajax来动态生成表格行。我想为每个表格行添加序列号,即 - td1。其他一切工作正常,请帮助我为每个tr添加序列号。在ajax中添加序列号到<tr>

<script> 
    $(document).ready(function() { 
     $('form').on('submit', function (e) { 
      e.preventDefault(); 
      ajx(); 
     }); 

     function ajx() { 
      $('tbody>tr').remove(); 
      var side = $('input[name=pins]:checked').val(); 
      $.ajax({ 
       beforeSend: function() { 
        $('#loader').show(); 
       }, 
       complete: function() { 
        $('#loader').hide(); 
       }, 
       url: "<?php echo base_url('user/genealogy/ajaxLevels')?>", 
       type: "POST", 
       dataType: 'json', 
       data: { 
        side: side 
       }, 
       success: function (result) 
       { 

        var obj = jQuery.parseJSON(JSON.stringify(result)); 
        var id = "#tbl"; 
        $.each(obj, function() { 
         var row = $('<tr>'); 
         var td1 = $('<td />'); 
         var td2 = $('<td />'); 
         var td3 = $('<td />'); 
         var td4 = $('<td />'); 
         var td5 = $('<td />'); 

         td1.text('1'); // I WANT TO ADD SERIAL NUMBER HERE 
         td2.text(this.name); 
         td3.text(this.id); 
         td4.text(this.date); 
         td5.text(this.sponsor_id); 

         row.append(td1); 
         row.append(td2); 
         row.append(td3); 
         row.append(td4); 
         row.append(td5); 

         $(id).append(row); 
        }); 
       } 

      }); 
     } 
    }); 

这是该数据将显示表:

<table class="table"> 
    <thead class="text-primary"> 
     <th>S.No.</th> 
     <th>Name</th> 
     <th>Member ID</th> 
     <th>DOJ</th> 
     <th>Sponser ID</th> 
    </thead> 
    <tbody id="tbl"> 
    </tbody> 
</table> 
+0

你想让数字像1,2,3,4 ...还是别的吗? –

+0

是的,1,2,3,4,5,6 ...... –

回答

0

你可以只用设置好的来1作为开始值的变量。
然后在每次迭代中增加这个变量。

success: function (result) 
    { 

    var obj = jQuery.parseJSON(JSON.stringify(result)); 
    var id = "#tbl"; 

    // use i as a counter 
    var i = 1; 

    $.each(obj, function() { 
     var row = $('<tr>'); 
     var td1 = $('<td />'); 
     var td2 = $('<td />'); 
     var td3 = $('<td />'); 
     var td4 = $('<td />'); 
     var td5 = $('<td />'); 

     td1.text(i); // Use i here 
     td2.text(this.name); 
     td3.text(this.id); 
     td4.text(this.date); 
     td5.text(this.sponsor_id); 

     row.append(td1); 
     row.append(td2); 
     row.append(td3); 
     row.append(td4); 
     row.append(td5); 

     $(id).append(row); 

     // Increment i for the next iteration 
     i++; 
    }); 
    } 
+0

谢谢,这很容易。 :) –

0

您还可以使用

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

您可以使用key + 1显示序列号。在每个功能键总是从0开始。