html使用jQuery编辑表格

43次阅读
没有评论

当需要编辑表格中的数据时,一个非常实用的功能就是可以直接在表格中编辑并保存数据,这就是可编辑表格。使用jQuery,我们可以很容易地实现这个功能。下面是一个完整的HTML页面示例:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>可编辑表格示例</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
      table {
        border-collapse: collapse;
        width: 100%;
        max-width: 600px;
        margin: 0 auto;
      }

      th, td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
      }

      th {
        background-color: #eee;
      }

      td[contenteditable=true] {
        background-color: #fff;
        font-weight: bold;
        cursor: text;
      }
    </style>
  </head>
  <body>
    <table id="editable-table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Phone</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td contenteditable="true">John Doe</td>
          <td contenteditable="true">johndoe@example.com</td>
          <td contenteditable="true">555-555-5555</td>
        </tr>
        <tr>
          <td contenteditable="true">Jane Doe</td>
          <td contenteditable="true">janedoe@example.com</td>
          <td contenteditable="true">555-555-5555</td>
        </tr>
      </tbody>
    </table>

    <button id="save-btn">保存</button>

    <script>
      $(document).ready(function() {
        // 点击按钮时保存表格中的数据
        $('#save-btn').click(function() {
          var tableData = [];
          $('#editable-table tbody tr').each(function(row, tr) {
            tableData[row] = {
              "name": $(tr).find('td:eq(0)').text(),
              "email": $(tr).find('td:eq(1)').text(),
              "phone": $(tr).find('td:eq(2)').text()
            }
          });
          // 在控制台中显示表格数据
          console.log(tableData);
        });
      });
    </script>
  </body>
</html>

这个示例包括一个包含一些数据的表格,一个保存按钮以及相关的CSS样式。表格中的每个单元格都被设置为可编辑,用户可以直接在单元格中进行编辑。当用户点击“保存”按钮时,页面会将表格数据保存为一个JSON对象并在控制台中显示。这是一个简单的例子,你可以在此基础上添加更多功能,如表格排序、筛选、删除等等。

正文完
 
评论(没有评论)