2016-10-05 81 views
-1

所以我試圖將Url的數據追加到表頭。從URL調用的數據是一個字符串列表。正如你所看到的,我正試圖通過列表中的每個值,然後將其附加到我的表頭「數據」中。 但是,當我運行代碼沒有附加任何東西。我知道數據正在進入,因爲窗口警報正在顯示每個字符串。JQuery:追加到表頭

JQuery的:

$(document).ready(function() { 
    $.ajax({ 
     url: 'http://..../api/Dynamic?table=table1', 
     dataType: 'Json', 
     success: function (tableResults) { 
      var count = 0; 
      $.each(tableResults, function() { 
       window.alert(this); 
       $('#data th:last-child').append('<th><a id="count">' + this + '</a></th>'); 
       count++; 
      }); 
     } 
    }); 
}); 

HTML:

<table id="data" border="1" align="center" width="95%"> 
     <thead> 
      <tr> 
      </tr> 
     </thead> 
     <tbody> 
     </tbody> 
    </table> 

有什麼建議?

+0

你......附加一個日到日。這沒有意義。 –

回答

1

如果tableResults是一個字符串數組,你可以直接使用每個參數並避免計數變量,如下面的代碼片段(使用後而不是追加,因爲新的th元素必須遵循而不是最後一個子元素):

// 
 
// if thead does not exist 
 
// 
 
if ($('#data thead').length == 0) { 
 
    $('#data').append($('<thead/>')); 
 
} 
 

 
$.each(['email', 'address', 'country'], function (index, value) { 
 
    if ($('#data th:last-child').length == 0) { 
 
    // 
 
    // if there are no th 
 
    // 
 
    $('#data thead').append('<th><a id="count' + index + '"</a>' + value + '</th>'); 
 
    } else { 
 
    $('#data th:last-child').after('<th><a id="count' + index + '"</a>' + value + '</th>'); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<table id="data" border="1" align="center" width="95%"> 
 
    <thead> 
 
    <tr> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    </tbody> 
 
</table>

+0

如果桌面是空的,該怎麼辦? –

+0

我試過你的代碼,它沒有工作。 –

+0

是的,它與您的陣列相似,並且我沒有收到錯誤 –