You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS/HTML:点击表格编辑按钮后获取指定列值并传递至JS函数

解决表格行编辑按钮传递行信息到JavaScript的问题

别担心,这个场景太常见了,我给你分享几个项目里常用的靠谱方案:

方案一:用自定义data-*属性(最推荐,维护友好)

直接把行对应的person数据绑定到编辑按钮的自定义数据属性上,点击时直接读取就行,逻辑清晰还不容易出错。

修改你的Thymeleaf按钮代码:

<td>
  <button class="btn-sm btn-success edit-btn" 
          data-id="*{person.id}" 
          data-name="*{person.name}"
          data-email="*{person.email}" <!-- 按需添加其他需要的属性 -->
          role="button">
    Edit
  </button>
</td>

对应的JavaScript代码:

// 给所有编辑按钮绑定点击事件
document.querySelectorAll('.edit-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    // 从按钮的data属性里取出当前行的person数据
    const personId = this.dataset.id;
    const personName = this.dataset.name;
    const personEmail = this.dataset.email;

    // 把数据填充到模态框的表单字段(假设模态框有对应输入框)
    document.getElementById('modal-person-id').value = personId;
    document.getElementById('modal-person-name').value = personName;
    document.getElementById('modal-person-email').value = personEmail;

    // 打开模态框(这里用Bootstrap模态框示例,根据你用的框架调整)
    new bootstrap.Modal(document.getElementById('editModal')).show();
  });
});

提交AJAX时,直接从模态框取数据或者用刚才的变量就行,比如:

// 模态框提交按钮的点击事件
document.getElementById('submit-edit').addEventListener('click', function() {
  const personId = document.getElementById('modal-person-id').value;
  const updatedName = document.getElementById('modal-person-name').value;

  // 发送AJAX请求(Spring项目记得加CSRF令牌)
  fetch('/edit/' + personId, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': document.querySelector('meta[name="_csrf"]').content
    },
    body: JSON.stringify({ name: updatedName })
  })
  .then(response => response.json())
  .then(data => {
    // 请求成功后的处理:关闭模态框、更新表格行显示
    new bootstrap.Modal(document.getElementById('editModal')).hide();
    document.querySelector(`tr[data-person-id="${personId}"] .name-cell`).textContent = updatedName;
  })
  .catch(error => console.error('提交失败:', error));
});

方案二:通过行元素提取数据(无需额外属性)

如果不想加data属性,也可以通过按钮找到它所在的行,再从行的单元格里提取数据:

HTML代码(给行加个标识方便后续更新):

<tr data-person-id="*{person.id}">
  <td class="name-cell">*{person.name}</td>
  <td>*{person.email}</td>
  <td>
    <button class="btn-sm btn-success edit-btn" role="button">Edit</button>
  </td>
</tr>

JavaScript代码:

document.querySelectorAll('.edit-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    // 找到当前按钮所在的行
    const row = this.closest('tr');
    // 从行内单元格提取数据(注意列顺序要和表格对应)
    const personId = row.dataset.personId;
    const personName = row.querySelector('.name-cell').textContent.trim();
    const personEmail = row.querySelectorAll('td')[1].textContent.trim(); // 第二列的内容

    // 后续步骤和方案一一致:填充模态框、打开模态框
  });
});

小提醒

  • 如果你用Spring Boot + Thymeleaf,一定要处理CSRF令牌,不然AJAX POST请求会被拦截,上面的例子已经加了相关代码。
  • 要是person属性特别多,可以把整个对象转成JSON字符串放到data属性里:data-person='[[${#json.toJson(person)}]]',JS里用JSON.parse(this.dataset.person)解析就行,更省心。

内容的提问来源于stack exchange,提问作者Anna Klein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:53:32