为什么我的代码不向表格元素追加新行?

时间:2019-06-01 03:06:32

标签: jquery

我的目的是在表格按钮元素上添加新行,但是当我单击按钮元素时没有任何反应。

我尝试检查是否选择了错误的元素,但是似乎所有内容都已被感性地反映。当我尝试在控制台中调试代码时,找不到任何要修复的错误。谢谢您的任何投入或帮助。

<!DOCTYPE html>
<html>

<head>
  <title>Table project</title>
  <style>
    table {
      background-color: #00FFFF;
    }
  </style>
</head>

<body>
  <table id="x" border="1">
    <thead>
      <tr id="row0">
        <th scope="col">#</th>
        <th scope="col">First</th>
        <th scope="col">Last</th>
        <th scope="col">Handle</th>
      </tr>
    </thead>
    <tbody id="tbody2">
      <tr id="row1">
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr id="row2">
        <th scope="row">2</th>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr id="row3">
        <th scope="row">3</th>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
    </tbody>
  </table>

  <button id="btn"> Enter Row </button>





  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

  <script type="text/javascript">
    $(document).ready(function() {
      $('#btn').click(function() {
        $("#x tbody2").append(
          "<tr>" +
          "<td>Shit</td>" +
          "<td>All over</td>" +
          "<td>Myself</td>" +
          "</tr>"
        );

      })
    })
  </script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您可以使用$("#tbody2")选择正文。使用$("#tbody2 > tr").length获取<tr>

的计数

<!DOCTYPE html>
<html>

<head>
  <title>Table project</title>
  <style>
    table {
      background-color: #00FFFF;
    }
  </style>
</head>

<body>
  <table id="x" border="1">
    <thead>
      <tr id="row0">
        <th scope="col">#</th>
        <th scope="col">First</th>
        <th scope="col">Last</th>
        <th scope="col">Handle</th>
      </tr>
    </thead>
    <tbody id="tbody2">
      <tr id="row1">
        <td scope="row">1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr id="row2">
        <td scope="row">2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr id="row3">
        <td scope="row">3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
    </tbody>
  </table>

  <button id="btn"> Enter Row </button>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

  <script type="text/javascript">
    $(document).ready(function() {
      $('#btn').click(function() {

        var count = $("#tbody2 > tr").length + 1;

        $("#tbody2").append(
          "<tr id='row" + count + "'>" +
          "<td scope='row'>" + count + "</td>" +
          "<td>Shit</td>" +
          "<td>All over</td>" +
          "<td>Myself</td>" +
          "</tr>"
        );

      })
    })
  </script>
</body>

</html>