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

如何在jQuery中为循环生成的动态表格行传递点击事件数据

问题描述

我有如下对象数组:

const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]

对应的HTML代码片段为:

<table id="NameTable">
  <thead>
    <tr>
          <th>Name</th>
     </tr>
   </thead>
   <tbody>
   </tbody>
</table>

我已通过以下代码利用数组数据动态填充表格:

array.forEach(person=> {
  $("#NameTable tbody").append(`<tr><td>   ${person.name} </td></tr>` )
})

表格已正常加载数据。现在我希望点击每行时调用如下函数,并传递对应的person对象:

function call(personObj){
   console.log(personObj)
}

请问如何通过jQuery实现点击每行时调用该函数并传递对应数据?

解决方案

方法一:生成行时直接绑定点击事件

在动态创建<tr>元素的同时,直接为其绑定点击事件,传入当前的person对象:

array.forEach(person=> {
  // 创建行元素并绑定点击逻辑
  const row = $(`<tr><td>   ${person.name} </td></tr>`);
  row.click(() => {
    call(person);
  });
  $("#NameTable tbody").append(row);
})

这种方式逻辑直接,生成元素时就关联对应数据,不容易出现匹配错误。

方法二:利用data()存储数据+事件委托

把person对象存储在行元素的自定义数据中,再通过事件委托统一绑定点击事件:

  1. 填充表格时存储数据
array.forEach(person=> {
  // 将对象转为字符串存入data属性
  $("#NameTable tbody").append(`<tr data-person='${JSON.stringify(person)}'><td>   ${person.name} </td></tr>` )
})
  1. 绑定事件委托
$("#NameTable tbody").on('click', 'tr', function() {
  // 取出存储的字符串并转回对象
  const personObj = JSON.parse($(this).data('person'));
  call(personObj);
})

该方法适合后续需要动态新增行的场景,事件只需绑定一次,就能作用于当前和未来的行元素。

方法三:通过索引匹配数组元素

如果数组内容不会变动,可通过行的索引关联对应数组元素:

  1. 填充表格时记录索引
array.forEach((person, index)=> {
  $("#NameTable tbody").append(`<tr data-index='${index}'><td>   ${person.name} </td></tr>` )
})
  1. 点击时通过索引取数据
$("#NameTable tbody").on('click', 'tr', function() {
  const index = $(this).data('index');
  const personObj = array[index];
  call(personObj);
})

这种方式不需要序列化对象,适合数组稳定的场景。

内容的提问来源于stack exchange,提问作者Ghias Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:05:11