How to access a specific cell of a row with a pressed table in javascript

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

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

Now I can get the full values ​​of the rows by clicking on any row. Now I need to access a single cell value in this function. Can someone tell me how I get the value of a single cell when I click on a row.

+5
source share
5 answers

Take a look at this:

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

Here is the working code: http://jsfiddle.net/VbA9D/

If you have other HTML elements inside the table cells that you could click on, the example below 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]':'') );
        });
    });
});

, :

http://jsfiddle.net/7PWu5/

+7

-, .each - .click , .

-, , cells , :

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

- , , , ( ).

+5

,

 alert($('td', this).eq(1).text());

,

 alert($('td.myclass', this).text());

, , :

$(".TreeTable  td").click(function() { // td not tr
     alert($(this).text());
});

, jQuery , .

+1

:

$('.TreeTable').on('click', 'td', function() { // td not tr
     alert($(this).text());
});
+1

.each() , . - <tr> event.target ( ), , (<td>):

$(function() {
    $('.TreeTable tr').click(function(event) {
        console.log(this); // the <tr>
        console.log(event.target); // the <td>
    });
});

, <td>, .

+1

All Articles