如何在javascript中访问单击表行的特定单元格

Ash*_*ore 5 html javascript css jquery

我有一个从数据库填充的HTML表.还有一个jquery函数,它将客户端点击事件添加到每个表行.

$(function() {
    $(".TreeTable tr").each(function(index) {
        $(this).click(function() {
            alert($(this).text());
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

现在,我可以通过单击任何行来获得完整的行值.现在我需要访问该函数中的单个单元格值.任何人都可以告诉我如何在行单击时获得单个单元格值.

leo*_*nfo 8

看看这个:

$(document).ready(function(){
    $('.TreeTable tr').click(function(e){
        var cell = $(e.target).get(0); // This is the TD you clicked
        var tr = $(this); // This is the TR you clicked
        $('#out').empty();
        $('td', tr).each(function(i, td){
            $('#out').html(
              $('#out').html()
              +'<br>'
              +i+': '+$(td).text() 
              + (td===cell?' [clicked]':'') );
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

这是工作代码:http: //jsfiddle.net/VbA9D/

如果在您可能单击的表格单元格中有其他HTML元素,则以下示例将更好地工作:

$(document).ready(function(){
    $('.TreeTable tr').click(function(e){
        var cell = $(e.target).get(0); // This is the TD you clicked
        if(cell.nodeName != 'TD') 
            cell = $(cell).closest('td').get(0);
        var tr = $(this); // This is the TR you clicked
        $('#out').empty();
        $('td', tr).each(function(i, td){
            $('#out').html(
              $('#out').html()
              +'<br>'
              +i+': '+$(td).text() 
              + (td===cell?' [clicked]':'') );
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

这是您可以测试的代码:

http://jsfiddle.net/7PWu5/


Aln*_*tak 5

首先,不需要.each- 该.click方法将绑定到每个传递的元素,而不仅仅是第一个元素.

其次,cells在表行元素上调用了一个特定的属性,可以直接访问行的单元格:

$('.TreeTable').on('click', 'tr', function() {
    var td = this.cells[0];  // the first <td>
    alert( $(td).text() );
});
Run Code Online (Sandbox Code Playgroud)

请注意事件委托的使用 - 事件处理程序实际上是在整个表上注册的,然后依赖于事件冒泡来告诉您单击了哪一行(并从中获取单元格文本).