2016-10-05 85 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

是的,它与您的阵列相似,并且我没有收到错误 –