jQuery:获取 HTML 表第四行(仅)的第一列值

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

本文关键字:一列 四行 获取 HTML jQuery      更新时间:2023-09-26

我有一个名为resultGridTable的表。我有一个jQuery函数要在表的每一行上执行。 在函数中,"this"表示一行。

    对于第四行
  1. ,我需要提醒第一列值(第四行)。我有以下代码;但它不起作用。我们如何才能使其发挥作用?

  2. 对于第五行,我需要提醒行中的列数。我们该怎么做?

  3. 在第六行的第二列中,我有两个按钮(输入类型="提交")。我需要提醒第二个按钮的文本/值。(第二个按钮有一个名为"secondButton"的类)我们该怎么做?

以下是代码:

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

读数:

  1. jQuery 代码:从父级到子级;而不是从子级到父级

  2. 如何使用jQuery获取html表中当前行中第一列的值

  3. 如何使用 jQuery 获取 Html 表的第一行的最后一列

为了与众不同,你可以在这里混合 DOM 和 jQuery 以获得良好的效果,因为你已经将偏移量固定到表中:

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();

这些都应该比使用选择器快得多。

查看 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());

如果你对行/列有特殊的值,请考虑添加一个类,然后你可以使用选择器而不是可能会改变的"魔术"数字。

改编自公认的答案。如果您使用的是 jquery 而不是 document.getElementById,这就是代码 不同之处在于您需要插入 [0] 的数组。

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