简体   繁体   中英

jQuery: Get First Column Value on Fourth Row (only) of HTML Table

I have a table named resultGridTable. I have a jQuery function to be executed on each row of the table. In the function, "this" means a row.

  1. For the fourth row, I need to alert the first column value (of fourth row). I have the following code; but it does not work. How can we make it working?

  2. For the fifth row, I need to alert the number of columns in the row. How can we do it?

  3. In the sixth row's second column, I have two buttons (input type="submit"). I need to alert the second button's text/value. (The second button has a class named "secondButton") How can we do it?

Following is the code::

$('#resultGridTable tr').each(function (i) 
{
    //"this" means row
    //Other operations in the row. Common for all rows

    if(i==3)
    {
        //Specific Operation for fourth row
        var columnValue = $(this 'td:nth-child(0)').val();
        alert(columnValue);
    }
});

READINGS:

  1. jQuery Code: Starting from Parent to Child; not from Child to Parent

  2. How to get value of first column in current row in html table using jQuery

  3. How to get the first row's last column of an Html table using jQuery

Just to be different, you can mix up DOM and jQuery to good effect here since you have fixed offsets into the table:

var t = document.getElementById('resultGridTable');

// jQuery to get the content of row 4, column 1
var val1 = $(t.rows[3].cells[0]).text();  

// no jQuery here to get that row length!
var val2 = t.rows[4].cells.length;       

// DOM access for the cell, and jQuery to find by class and get the text 
var val3 = $('.secondButton', t.rows[5].cells[1]).text();

These should all be substantially faster than using selectors.

Look into jQuery eq :

alert($('#resultGridTable tr:eq(3) > td:eq(0)').text());
alert($('#resultGridTable tr:eq(4) > td').length);
alert($('#resultGridTable tr:eq(5) > td:eq(1) > .secondButton').text());

如果你有行/列的特殊值,考虑添加一个类,那么你可以使用选择器而不是可能改变的“魔术”数字。

Adapted from Accepted Answer. This is the code if you are using jquery instead of document.getElementById The difference is that you need to insert the array of [0].

 var t = $('resultGridTable');

// jQuery to get the content of row 4, column 1
var val1 = $(t[0].rows[3].cells[0]).text();  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM