如何使用jQuery获取被点击的表格表头th元素的id属性值
问题
当点击表格表头行时,需要通过通用函数获取被点击的<th>元素的id,无需为每个表头项单独编写处理函数。当前使用jQuery进行开发,现有代码如下:
HTML代码
<div id="title"> <table class="policies sortable"> <thead id="h-th"> <tr id="h-tr"> <th width="3%" id="h-client">Client</th> <th width="7%" id="h-company-code">Company Code</th> <th width="9%" id="h-unique-reference">Unique Reference</th> <th width="8%" id="h-doc-date">Document Date</th> <th width="8%" id="h-post-date">Posting Date</th> <th width="7%" id="h-doc-type">Document Type</th> <th width="5%" id="h-trip-id">Trip Id</th> <th width="7%" id="h-ticket-no">Ticket Number</th> <th width="6%" id="h-calc-tax">Calculate Tax</th> <th width="15%" id="h-passenger-name">Passenger Name</th> <th width="4%" id="h-error">Valid</th> <th width="4%" id="h-processed">Processed</th> <th width="4%" id="h-payment">Payment</th> <th width="11%" id="h-updated">Updated</th> </tr> </thead> </table> </div>
现有JavaScript代码
$("#h-tr").click(function(item) { console.log(item); // get the id of the clicked <th> });
解决方案
直接通过事件对象的target属性获取实际触发点击的元素即可,无需额外给每个th绑定事件。修改后的代码如下:
$("#h-tr").click(function(e) { // 获取实际被点击的元素 const clickedTh = e.target; // 确认点击的是th元素后再拿id if (clickedTh.tagName === 'TH') { const thId = clickedTh.id; console.log('被点击的表头id是:', thId); // 后续业务逻辑直接使用thId即可 } });
如果希望写法更贴合jQuery的风格,也可以用$(e.target)来包装元素,兼容性更强,就算th内部嵌套了其他子元素,也能正确找到上层的th元素获取id:
$("#h-tr").click(function(e) { const $th = $(e.target).closest('th'); if ($th.length) { const thId = $th.attr('id'); console.log('被点击的表头id是:', thId); } });
内容的提问来源于stack exchange,提问作者Richard
相关产品推荐
相关产品推荐

