2016-10-05 8 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が文字列の配列である場合は、次のスニペットのように、各パラメータを直接使用してcount変数を使用することができます(appendの代わりにafterを使用します。 ):

// 
 
// 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

はい、あなたの配列に似ていますが、エラーは発生しません –

関連する問題