如何使用jQuery获取表格单元格值?


213

我正在尝试找出如何使用jQuery获取每一行的表格单元格的值。

我的桌子看起来像这样:

<table id="mytable">
  <tr>
    <th>Customer Id</th>
    <th>Result</th>
  </tr>
  <tr>
    <td>123</td>
    <td></td>
  </tr>
  <tr>
    <td>456</td>
    <td></td>
  </tr>
  <tr>
    <td>789</td>
    <td></td>
  </tr>
</table>

我基本上想遍历表,并获取Customer Id每一行的列值。

在下面的代码中,我已经确定需要执行此操作以使其遍历每一行,但是我不确定如何获取该行中第一个单元格的值。

$('#mytable tr').each(function() {
    var cutomerId = 
}

4
这是完整的现场演示教程,内容涉及如何获取表单元格TD值codepedia.info/jquery-get-table-cell-td-value-div
Satinder singh

Answers:


306

如果可以的话,可能值得在TD上使用包含客户ID的class属性,这样您就可以编写:

$('#mytable tr').each(function() {
    var customerId = $(this).find(".customerIDCell").html();    
 });

从本质上讲,这与其他解决方案相同(可能是由于我复制粘贴了),但具有的优点是,如果您在列中四处移动甚至将客户ID放入列表中,都无需更改代码的结构。<span>,前提是您保留了class属性。

顺便说一句,我认为您可以在一个选择器中完成此操作:

$('#mytable .customerIDCell').each(function() {
  alert($(this).html());
});

如果这样会使事情变得容易。


4
我会说$('#mytable td.customerIDCell')。each(function(){alert($(this).html());}); 但+1
马特·布里格斯

:-)谢谢-但是,如果您想将其放入跨度(我的答案中的跨度可能格式错误!)
Jennifer

2
如果您碰巧在<tfoot>中有<td>(或者正在使用<td>而不是<th>)并且不想要这些,则在tr上使用该类特别有用。
弗兰克·卢克

$('#mytable tr')。each(function(){var customerId = $(this).find(“。customerIDCell”)。html();});
Osama khodrog 2012年

但是,如果我还想获取tr html,那么我们可以做什么
开发人员

132
$('#mytable tr').each(function() {
    var customerId = $(this).find("td:first").html();    
});

您正在做的事情是遍历表中的所有tr,在循环中找到当前tr中的第一个td,并提取其内部html。

要选择特定的单元格,可以使用索引引用它们:

$('#mytable tr').each(function() {
    var customerId = $(this).find("td").eq(2).html();    
});

在上面的代码中,我将检索第三行的值(索引从零开始,因此第一个单元格索引将为0)


没有jQuery的方法如下:

var table = document.getElementById('mytable'), 
    rows = table.getElementsByTagName('tr'),
    i, j, cells, customerId;

for (i = 0, j = rows.length; i < j; ++i) {
    cells = rows[i].getElementsByTagName('td');
    if (!cells.length) {
        continue;
    }
    customerId = cells[0].innerHTML;
}


1
谢谢,这对我来说更有用,因为我无法控制要使用jQuery解析的文档的标记。因此,能够使用“ td:first”,“ td:last”等非常有用。
原子

1
eq(2)将获得第三列而不是第三行的值。
现场直播

您的代码中的eq(2)是什么?我的意思是2是哪个td或tr的索引?
TechnicalKalsa

@Singh 函数td返回的集合的索引2处的元素find("td")
Andreas Grech

我喜欢索引为ref的选项2,在这里
HattrickNZ 2015年

18

一种不太拘泥的方法:

$('#mytable tr').each(function() {
    if (!this.rowIndex) return; // skip first row
    var customerId = this.cells[0].innerHTML;
});

显然,可以将其更改为与非第一单元一起使用。


8
$('#mytable tr').each(function() {
  // need this to skip the first row
  if ($(this).find("td:first").length > 0) {
    var cutomerId = $(this).find("td:first").html();
  }
});

2
无需跳过第一行,因为它包含<th>,而不是<td>,因此不会提取其数据
Andreas Grech

7

试试这个,

$(document).ready(function(){
$(".items").delegate("tr.classname", "click", function(data){
            alert(data.target.innerHTML);//this will show the inner html
    alert($(this).find('td:eq(0)').html());//this will alert the value in the 1st column.
    });
});

1
第二个元素(不是第一个元素)的等式从0开始
Claudiu Creanga

4

是不是您在该栏使用ID?比如说:

    <table width="300" border="1">
          <tr>
            <td>first</td>
          </tr>
          <tr>
            <td>second</td>
          </tr> 
          <tr>
            <td>blah blah</td>
            <td>blah blah</td>
            <td id="result">Where the result should occur</td>
          </tr>
    </table>


<script type="text/javascript">
        $('#result').html("The result is....");
</script>

4

这有效

$(document).ready(function() {
    for (var row = 0; row < 3; row++) {
        for (var col = 0; col < 3; col++) {
            $("#tbl").children().children()[row].children[col].innerHTML = "H!";
        }
    }
});

2

试试这个 :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>

<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    alert(targ.innerHTML);
}

onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;
}

</script>



<body>

<table id="main"><tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr><tr>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr><tr>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
</tr></table>

</body>
</html>

2
$(document).ready(function() {
     var customerId
     $("#mytable td").click(function() {
     alert($(this).html());
     });
 });

2

一个有效的示例:http : //jsfiddle.net/0sgLbynd/

<table>
<tr>
    <td>0</td>
    <td class="ms-vb2">1</td>
    <td class="ms-vb2">2</td>
    <td class="ms-vb2">3</td>
    <td class="ms-vb2">4</td>
    <td class="ms-vb2">5</td>
    <td class="ms-vb2">6</td>
</tr>
</table>


$(document).ready(function () {
//alert("sss");
$("td").each(function () {
    //alert($(this).html());
    $(this).html("aaaaaaa");
});
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.