动态生成的表显示有错误

时间:2014-10-19 13:37:24

标签: javascript css json twitter-bootstrap

我正在尝试使用bootstrap类正确显示表。该表是从json文件动态生成的。

问题在于,当我使用工具检查元素时,即使它们显示在表中,它们也不会获得引导类,因为这些属性在我想要之前关闭。这是我的代码:

      // Makes the request to searches @ Reddit using the Reddit API
  $.getJSON(
    "http://www.reddit.com/r/entrepreneur/search.json?q=" + searchString + "&sort=hot",
    function foo(data)
    {
      //Initializes the table   
        $("#reddit-content").append( '<table class="table table-striped">' );

        $("#reddit-content").append('<thead>');
        $("#reddit-content").append('<tr>');
        $("#reddit-content").append('<th>Title</th>');
        $("#reddit-content").append('<th>Ups</th>');
        $("#reddit-content").append('<th>Downs</th>');
        $("#reddit-content").append('<th>Date</th>');
        $("#reddit-content").append('<th>Visit</th>');
        $("#reddit-content").append('</tr>');
        $("#reddit-content").append('</thead>');
        $("#reddit-content").append('<tbody>');

      $.each(
        data.data.children.slice(0, 25),
        function (i, post) {

        // create a new javascript Date object based on the timestamp
        // multiplied by 1000 so that the argument is in milliseconds, not seconds
        var date = new Date( post.data.created_utc * 1000 );
        // hours part from the timestamp
        var hours = date.getHours();
        // minutes part from the timestamp
        var minutes = "0" + date.getMinutes();
        // seconds part from the timestamp
        var seconds = "0" + date.getSeconds();
        // Formats the date object for proper viasualization
        var formattedTime = hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);

          $("#reddit-content").append('<tr>');
          $("#reddit-content").append( '<td>' + post.data.title + '</td>');
          $("#reddit-content").append( '<td>' + post.data.ups + '</td>');
          $("#reddit-content").append( '<td>' + post.data.downs + '</td>');
          $("#reddit-content").append( '<td>' + formattedTime + '</td>');
          $("#reddit-content").append( '<td>' + post.data.permalink + '</td>');
          $("#reddit-content").append('</tr>');
        }
      )
      //Ends the table
      $("#reddit-content").append('</tbody>');
      $("#reddit-content").append( '</table>' );
    }
  )

在下图中,您可以看到标签在打开后正在关闭,这样我就无法将bootstrap CSS应用到它。

enter image description here

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:1)

您只会追加$("#reddit-content")。您需要将内容附加到相应的父级。像这样:

var $table = $("#reddit-content").append( '<table class="table table-striped">' );
$table.append('<thead><tr><th>...</thead>');
$table.append('<tr>..</tr>');
        :