2016-07-15 32 views
0

當我的數據來自json和我試圖使用此代碼爲我的數據表添加行時。但它沒有奏效。我怎樣才能解決這個問題 ?使用javascript將行添加到html表格

<table style="width:300px" > 
    <thead> 
      <th> 
       Name 
      </th> 


    </thead> 
    <tbody id="location"> 


    </tbody> 
</table> 

$.ajax(
    { 
     type: "GET", 
     url: 'http://jsonplaceholder.typicode.com/users', 
     data: "{}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     cache: false, 
     success: function (data) { 

      var trHTML = ''; 
      for (var i = 1; i > data.length; i++) { 
       console.log(data[i].name); 
       trHTML += '<tr><td><span>' + data[i].name + '</span></td></tr>'; 

      }; 
      $('#location tbody').append(trHTML); 


     }, 

     error: function (msg) { 

      alert(msg.responseText); 
     } 
    }); 

我的實際目標是將行footable數據表插件,但我不能修復它。

+0

將'$('#location tbody')。append(trHTML)'改爲'$('#location')。append(trHTML)' – Azim

+2

.length – Rakshith

+1

i

回答

1

您的代碼有幾個問題。大多數已在評論中提及:

1)由於條件i > data.length從不爲真,因此您的循環不起作用。我建議使用jQuery.each(...)來循環數據。或者將其修復爲i < data.length,但您還必須從var i = 0開始。

2)$('#location tbody')不存在於您的html中。這將是ID爲location的元素內的tbody元素。你想$('tbody#location')或只是$('#location'),因爲你不應該在你的html中有多個具有相同ID的項目。

3)你的html裏面的thead是不正確的。它會以這種方式工作,但它不是乾淨的HTML。

希望此列表有所幫助。它基本上總結了評論。 (感謝所有你們在這裏!)

+0

請注意我在循環中用'var i = 0'編輯...否則,你將失去一個元素數據。 – TehSphinX