首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用Javascript使表格行可在单击时编辑

的方法如下:

  1. 首先,为表格的每一行添加一个点击事件监听器,当行被点击时触发编辑模式。
  2. 在点击事件处理程序中,获取当前被点击的行,并将其转换为可编辑状态。
  3. 创建一个保存按钮,当点击保存按钮时,将编辑后的数据保存并退出编辑模式。
  4. 添加取消按钮,当点击取消按钮时,放弃编辑并恢复原始数据。
  5. 使用HTML的contenteditable属性使表格单元格可编辑。

下面是一个示例代码:

代码语言:txt
复制
<!DOCTYPE html>
<html>
<head>
  <style>
    table {
      border-collapse: collapse;
    }
    td, th {
      border: 1px solid black;
      padding: 8px;
    }
  </style>
</head>
<body>
  <table id="myTable">
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Action</th>
    </tr>
    <tr>
      <td contenteditable="true">John Doe</td>
      <td contenteditable="true">johndoe@example.com</td>
      <td>
        <button onclick="editRow(this)">Edit</button>
        <button onclick="saveRow(this)">Save</button>
        <button onclick="cancelEdit(this)">Cancel</button>
      </td>
    </tr>
    <tr>
      <td contenteditable="true">Jane Smith</td>
      <td contenteditable="true">janesmith@example.com</td>
      <td>
        <button onclick="editRow(this)">Edit</button>
        <button onclick="saveRow(this)">Save</button>
        <button onclick="cancelEdit(this)">Cancel</button>
      </td>
    </tr>
  </table>

  <script>
    function editRow(button) {
      var row = button.parentNode.parentNode;
      var cells = row.getElementsByTagName("td");
      for (var i = 0; i < cells.length - 1; i++) {
        cells[i].setAttribute("contenteditable", "true");
      }
      button.style.display = "none";
      row.querySelector("button:nth-of-type(2)").style.display = "inline";
      row.querySelector("button:nth-of-type(3)").style.display = "inline";
    }

    function saveRow(button) {
      var row = button.parentNode.parentNode;
      var cells = row.getElementsByTagName("td");
      for (var i = 0; i < cells.length - 1; i++) {
        cells[i].setAttribute("contenteditable", "false");
      }
      button.style.display = "none";
      row.querySelector("button:nth-of-type(1)").style.display = "inline";
      row.querySelector("button:nth-of-type(3)").style.display = "none";
    }

    function cancelEdit(button) {
      var row = button.parentNode.parentNode;
      var cells = row.getElementsByTagName("td");
      for (var i = 0; i < cells.length - 1; i++) {
        cells[i].setAttribute("contenteditable", "false");
        cells[i].innerText = cells[i].getAttribute("data-original-value");
      }
      button.style.display = "none";
      row.querySelector("button:nth-of-type(1)").style.display = "inline";
      row.querySelector("button:nth-of-type(2)").style.display = "none";
    }
  </script>
</body>
</html>

这段代码创建了一个简单的表格,每一行都有一个编辑按钮。当点击编辑按钮时,对应行的单元格将变为可编辑状态。保存按钮用于保存编辑后的数据,取消按钮用于放弃编辑并恢复原始数据。

请注意,这只是一个简单的示例,实际应用中可能需要更复杂的逻辑和验证。此外,这个示例中使用了纯Javascript和HTML来实现,没有使用任何特定的云计算产品。

希望这个答案能够满足你的需求。如果有任何问题,请随时提问。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券