单击特定列时获取表行单元格值

时间:2013-07-16 07:00:20

标签: javascript jquery

我能够通过表单击事件检索所有行值,并通过event.currentTarget.cells[4].innerText();获取其值。

但是,如果仅点击特定列,我会想要应用此功能,例如,当我点击ID 21下的Username column时。它应该警告该行的所有单元格值。然后,当我点击其他列时,它不应该发出警报。

这是我的代码。如果您遇到问题,请通知我。

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        $('#tableid').on('click', 'tr', function (event) {
            alert(event.currentTarget.cells[0].innerText);
            alert(event.currentTarget.cells[1].innerText);
            alert(event.currentTarget.cells[2].innerText);
            alert(event.currentTarget.cells[3].innerText);
            alert(event.currentTarget.cells[4].innerText);
        });
    });
</script>

这是我的HTML http://jsfiddle.net/jE5UM/

2 个答案:

答案 0 :(得分:0)

我建议,在没有特定HTML和其他信息的情况下:

$(document).ready(function () {
    $('#tableid').on('click', 'tr', function (event) {
        var cell = event.target,
            values = $(cell).siblings().addBack().map(function(){
                         return $(this).text();
                     }).get();
        alert(values);
    });
});

JS Fiddle demo

参考文献:

答案 1 :(得分:0)

尝试

$(document).ready(function () {
    $('#tableid').on('click', 'tr', function (event) {                
        $(this).children().each(function(){
            alert($(this).text())
        })
    });
});

演示:Fiddle

如果你想要一个数组作为结果

$(document).ready(function () {
    $('#tableid').on('click', 'tr', function (event) {                
        var texts = $(this).children().map(function(){
            return $.trim($(this).html())
        }).get();
    });
});

演示:Fiddle

更新

$(document).ready(function () {
    $('#tableid').on('click', 'tr td:nth-child(2)', function (event) {                
        var texts = $(this).closest('td').siblings().addBack().map(function(){
            return $.trim($(this).html())
        }).get();
        alert(texts.join())
    });
});

演示:Fiddle

相关问题