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

如何获取按钮值追加到div表格 实现点击选中/再次点击移除效果

实现代码及说明

原有代码存在3个核心问题,对应修正逻辑如下:

  • .nr是input按钮元素,取值需要用.val()方法,.text()无法读取input的value属性
  • 要获取对应列的表头,先计算当前值所在<td>的列索引,再匹配表头对应位置的<th>文本即可
  • 实现点击选中/再次点击取消的切换效果,用class标记按钮选中状态,选中时追加带唯一标识的内容,取消时按标识删除对应内容即可
  • 额外注意:原HTML存在重复idresultas,id需页面唯一,先修正该结构问题

修正后的HTML结构(仅调整重复id部分)

<script src="jquery.min.js"></script>
<div class="cart">
  <div id="resultas"></div>
</div>
<table id="choose-address-table" class="ui-widget ui-widget-content" border="1">
  <thead>
    <tr class="ui-widget-header ">
      <th>Name/Nr.</th>
      <th>Street</th>
      <th>Town</th>
      <th>Postcode</th>
      <th>Country</th>
      <th>Options</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="button" class="nr" value="50"></td>
      <td>Some Street 1</td>
      <td>Leeds</td>
      <td>L0 0XX</td>
      <td>United Kingdom</td>
      <td>
        <button type="button" class="use-address">选择</button>
      </td>
    </tr>
    <tr>
      <td><input type="button" class="nr" value="49"></td>
      <td>Some Street 2</td>
      <td>Lancaster</td>
      <td>L0 0XX</td>
      <td>United Kingdom</td>
      <td>
        <button type="button" class="use-address">选择</button>
      </td>
    </tr>
  </tbody>
</table>

注:原button标签为自闭合写法且无文本,补充了按钮文字方便点击识别,可按需调整

核心JS逻辑

$(".use-address").click(function() {
  const $this = $(this);
  // 切换选中状态标记
  $this.toggleClass('selected');
  const isChecked = $this.hasClass('selected');

  // 获取当前行
  const $curRow = $this.closest('tr');
  // 读取按钮上的Nr值(input用val取值)
  const nrValue = $curRow.find('.nr').val();
  // 定位当前值所在列的索引,匹配对应表头
  const colIdx = $curRow.find('.nr').closest('td').index();
  const headerName = $('#choose-address-table thead th').eq(colIdx).text().trim();

  if (isChecked) {
    // 选中时追加内容,绑定data-nr作为唯一删除标识
    $('#resultas').append(`<div class="selected-item" data-nr="${nrValue}">${headerName}:${nrValue}</div>`);
    // 可选:选中状态下给按钮加样式/文字提示
    $this.text('取消选择');
  } else {
    // 取消选中时删除对应条目
    $(`#resultas .selected-item[data-nr="${nrValue}"]`).remove();
    // 恢复按钮默认文字
    $this.text('选择');
  }
});

如果需要结果区展示为表格格式,只需要把#resultas改为table容器,追加内容时输出<tr><td>${headerName}:${nrValue}</td></tr>结构即可。


内容的提问来源于stack exchange,提问作者Woza Station Namibia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 22:12:22