jquery - HTML 表格 jQuery : determining which column has been clicked when a cell is clicked if the TH has a unique data attribute value

标签 jquery html-table custom-data-attribute

如果表是这样定义的:

            <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);
});

JS Fiddle demo .

(请注意,通常情况下,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);
});

JS Fiddle demo .

以同样的方式,click 也可以绑定(bind)到 table 元素:

$('table').click(function (e) {
    var dataInfo = $('thead th').eq(e.target.cellIndex).data('info');
    console.log(dataInfo);
});

JS Fiddle demo .

引用文献:

关于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/

相关文章:

javascript - 无法让 jQuery 识别鼠标悬停在图像上

css - 如何对齐表单中的输入框

php - 如何使用 PHP 读取 CSV 文件并在 Table/DIV 中显示内容?

html - 为什么忽略列宽?

javascript - 编写干净的 jQuery

javascript - <td> 内的动态 anchor 标记

php - 选择提交表单的id以放入jquery变量

javascript - length 属性在 Firefox 和 IE/Chrome 之间的工作方式不同

javascript - IE 6 中的 HTML5 自定义数据属性是否为 “work”?

knockout.js - 使用knockoutjs attr来写入data*属性