如何使用jquery动态生成表

时间:2017-07-17 14:55:22

标签: jquery

我想在表格中生成从170的数字,每行只包含5个数字。我已经生成了这个,但我不知道如何在第五个</td>之后关闭表格行。我还希望它生成<a>标记。请帮帮我。

flag = false;
for (var i = 1; i <= 15; i++) {
  if (!flag) {
    $("tbody").append("<tr>")
    flag = true;
  }

  $('tr').append('<td><a data-index=' + i + '>' + i + '</a></td>');

  if (i % 5 == 0) {
    $("td:nth-child(5n)").insertAfter('</tr>');
    flag = false;
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="container">
    <h2>Bordered Table</h2>
    <p>The .table-bordered class adds borders to a table:</p>
    <table class="table table-bordered location">
      <tbody></tbody>
    </table>
  </div>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

我建议你使用这样的jQuery追加代码:

$('tbody').append(
   $('<tr>').append(
     $('td').append(
       $('a').attr('data-index', i)
      )
    )
 )

jQuery会自动关闭标签。

答案 1 :(得分:0)

这是一个小的逻辑变化。想法是在变量中构建所有td标记,当您将数字乘以5时,将其附加到tbody并将其附加到tr

&#13;
&#13;
var $tableBody = $('tbody'); // use a Id selector here
var rowHTML = '';

for (var i = 1; i <= 15; i++) {
  rowHTML += '<td><a data-index=' + i + '>' + i + '</a></td>';

  if (i % 5 == 0) {
    $tableBody.append('<tr>' + rowHTML + '</tr>');
    rowHTML = '';
  }
}
&#13;
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <h2>Bordered Table</h2>
    <p>The .table-bordered class adds borders to a table:</p>
    <table class="table table-bordered location">
      <tbody></tbody>
    </table>
  </div>
</body>

</html>
&#13;
&#13;
&#13;