如何访问javascript中被点击的表行的特定单元格 [英] How to access specific cell of clicked table row in javascript

查看:85
本文介绍了如何访问javascript中被点击的表行的特定单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据库填充的HTML表。
和一个jquery函数,它向每个表行添加客户点击事件。

I have an HTML table populated from database. And a jquery function that adds client click event to every table row.

$(function() {
    $(".TreeTable tr").each(function(index) {
        $(this).click(function() {
            alert($(this).text());
        });
    });
});



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

Now I am able to get complete row values by clicking on any row. Now I need to access individual cell value in that function. Can any one tell me how I get individual cell value on row click.

推荐答案

$(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]':'') );
        });
    });
});

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

如果表格单元格中有其他HTML元素点击,以下示例将会更好地工作:

In case you have other HTML elements inside the table cells on which you might click, the below example will work better:

$(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]':'') );
        });
    });
});

这里是您可以测试的代码:

And here is the code you can test:

http://jsfiddle.net/7PWu5/

这篇关于如何访问javascript中被点击的表行的特定单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆