如果表是这样定义的:
<colgroup>
<col style="width:100px;">
<col style="width:100px;">
</colgroup>
<thead>
<th class="foo" data-info="zipcode10023">
<th class="foo" data-info="zipcode60602">
</thead>
使得自定义属性data-info
中的值唯一,当单击表格中的单元格时,确定哪一列的最有效方法是什么已被单击(即为了获取数据信息值,例如“zipcode60606”)?
编辑:单击的单元格左侧可能有不可见的列。
最佳答案
假设在单元格上检测到点击:
$('td').click(function(){
var col = $(this).index(),
dataInfo = $('thead th').eq(col).attr('data-info');
/* or:
dataInfo = $('thead th').eq($(this).index()).attr('data-info');
or:
dataInfo = $('thead th').eq($(this).index()).data('info');
*/
});
JS Fiddle demo using: $('thead th').eq(col).attr('data-info')
.
JS Fiddle demo using: $('thead th').eq($(this).index()).attr('data-info')
.
JS Fiddle demo using: $('thead th').eq($(this).index()).data('info')
.
当然,您可以将事件处理程序放置在祖先元素上,例如 tr
,方法是:
$('tr').click(function (e) {
var dataInfo = $('thead th').eq(e.target.cellIndex).data('info');
console.log(dataInfo);
});
(请注意,通常情况下,event.target
不一定是跨浏览器兼容的,并且 Internet Explorer 可能需要(在 jQuery 之外)替代方案:window.event.srcElement
,但是 jQuery 规范了事件,这样 IE 不仅会读取/“理解”event
(并且不需要 window.event
),而且还会可以访问规范化的 event.target
。)
或者,to use enough jQuery :
$('tr').on('click', 'td', function (e) {
var dataInfo = $('thead th').eq($(this).index()).data('info');
console.log(dataInfo);
});
以同样的方式,click
也可以绑定(bind)到 table
元素:
$('table').click(function (e) {
var dataInfo = $('thead th').eq(e.target.cellIndex).data('info');
console.log(dataInfo);
});
引用文献:
关于jquery - HTML 表格 jQuery : determining which column has been clicked when a cell is clicked if the TH has a unique data attribute value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14637166/