如何使用jQuery获取点击表格用户名时对应行的checkbox值
实现思路
- 采用事件委托给表格绑定点击事件,仅监听Name列(第二列,索引为1)的单元格点击,性能更高,也兼容后续动态新增的表格行
- 点击事件触发后,先定位到当前单元格所属的整行,再查找该行首列的checkbox元素,直接读取其value值、选中状态即可
代码实现
原生JavaScript版本
const tableTbody = document.querySelector('table tbody'); tableTbody.addEventListener('click', function(e) { // 校验点击的是否是Name列的单元格 if (e.target.tagName.toLowerCase() === 'td' && e.target.cellIndex === 1) { const currentRow = e.target.closest('tr'); const targetCheckbox = currentRow.querySelector('input[type="checkbox"]'); // 可根据业务需求修改以下逻辑 console.log('点击的用户名:', e.target.textContent.trim()); console.log('对应checkbox的值:', targetCheckbox.value); console.log('对应checkbox是否选中:', targetCheckbox.checked); } });
jQuery版本(适用引入了jQuery的项目)
$('table tbody').on('click', 'td:nth-child(2)', function() { const $currentRow = $(this).closest('tr'); const $targetCheckbox = $currentRow.find('input[type="checkbox"]'); // 可根据业务需求修改以下逻辑 console.log('点击的用户名:', $(this).text().trim()); console.log('对应checkbox的值:', $targetCheckbox.val()); console.log('对应checkbox是否选中:', $targetCheckbox.is(':checked')); });
验证效果
点击Name列的Sam单元格时,会输出对应checkbox的值为1;点击Adem单元格时,会输出对应checkbox的值为2,同时可以拿到实时的选中状态。
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

