我试图弄清楚如何使用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 = 
}

当前回答

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

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

从本质上讲,这与其他解决方案是相同的(可能是因为我复制粘贴了),但它的优点是,如果在列之间移动,甚至不需要更改代码的结构,也不需要将客户ID放入<span>中,只要保留class属性即可。

顺便说一下,我认为你可以在一个选择器中完成:

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

如果这样能让事情简单些的话。

其他回答

试试这个,

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

这是

$(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!";
        }
    }
});

一个工作的例子: 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");
});
});
$('#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();
  }
});

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

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

从本质上讲,这与其他解决方案是相同的(可能是因为我复制粘贴了),但它的优点是,如果在列之间移动,甚至不需要更改代码的结构,也不需要将客户ID放入<span>中,只要保留class属性即可。

顺便说一下,我认为你可以在一个选择器中完成:

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

如果这样能让事情简单些的话。