ES6/Typescript实现:点击按钮为所在行除首个TD外添加类(无jQuery)
实现表格行按钮点击为指定单元格添加类(ES6/TypeScript版)
我来给你捋捋怎么搞定这个需求哈,全程用原生ES6/TypeScript实现,完全不用jQuery~
首先调整你的表格HTML
原来的按钮没法定位到自己所在的行,所以我们先给按钮加个小改动,让它点击时能把自身的引用传进去(或者用后面说的事件委托更优雅):
<table> <tr> <td>1</td> <td>joe</td> <td>brown</td> <td><button onclick="addClasses(this)">Add Class to TD's in this TR except the first one</button></td> </tr> <tr> <td>2</td> <td>bob</td> <td>blue</td> <td><button onclick="addClasses(this)">Add Class to TD's in this row except the first one</button></td> </tr> </table>
方案1:直接绑定按钮事件(ES6版)
写个简单的函数,接收按钮元素,找到对应行后给指定单元格加类:
function addClasses(button) { // 找到按钮所在的行 const row = button.closest('tr'); // 筛选出这一行除第一个TD外的所有单元格 const targetTDs = row.querySelectorAll('td:not(:first-child)'); // 给每个目标单元格添加类(这里用`highlight`作为示例类名,你可以改成自己需要的) targetTDs.forEach(td => td.classList.add('highlight')); }
方案1的TypeScript版本
只是加个类型注解,让代码更严谨,还加了空值判断避免报错:
function addClasses(button: HTMLButtonElement): void { const row = button.closest('tr'); if (!row) return; // 防止找不到行的情况 const targetTDs = row.querySelectorAll('td:not(:first-child)') as NodeListOf<HTMLTableCellElement>; targetTDs.forEach(td => td.classList.add('highlight')); }
方案2:事件委托(更优雅的写法)
如果表格行数很多,给每个按钮都加onclick会有点冗余,用事件委托只给表格加一个监听就行:
先修改HTML,去掉按钮的onclick,给表格加个ID方便定位:
<table id="userTable"> <tr> <td>1</td> <td>joe</td> <td>brown</td> <td><button>Add Class to TD's in this TR except the first one</button></td> </tr> <tr> <td>2</td> <td>bob</td> <td>blue</td> <td><button>Add Class to TD's in this row except the first one</button></td> </tr> </table>
然后是ES6实现:
// 找到表格元素 const userTable = document.getElementById('userTable'); // 给表格添加点击监听 userTable.addEventListener('click', (e) => { // 判断点击的是不是按钮 if (e.target.tagName === 'BUTTON') { const row = e.target.closest('tr'); const targetTDs = row.querySelectorAll('td:not(:first-child)'); targetTDs.forEach(td => td.classList.add('highlight')); } });
对应的TypeScript版本:
const userTable = document.getElementById('userTable'); if (userTable) { userTable.addEventListener('click', (e: MouseEvent) => { const target = e.target as HTMLElement; // 确认点击的是按钮 if (target.tagName === 'BUTTON') { const row = target.closest('tr'); if (!row) return; const targetTDs = row.querySelectorAll('td:not(:first-child)') as NodeListOf<HTMLTableCellElement>; targetTDs.forEach(td => td.classList.add('highlight')); } }); }
关键知识点说明
closest('tr'):原生DOM方法,能快速找到当前元素最近的父级<tr>,比一层层往上找parentNode高效多了td:not(:first-child):用CSS选择器直接筛选出目标单元格,简洁明了classList.add():原生方法,安全添加类名,就算类已经存在也不会重复添加,比直接操作className靠谱
内容的提问来源于stack exchange,提问作者user9273032
相关产品推荐
相关产品推荐

