2011-04-28 87 views
4

所以,如果我有表:如何使用JQuery或Javascript更改某行中某个特定TD的值?

<table id="someTable"> 
    <tr><td>Key1</td><td>Value1</td></tr> 
    <tr><td>Key2</td><td>Value2</td></tr> 
    <tr><td>Key3</td><td>Value3</td></tr> 
</table> 

有没有一种方法,我可以得到的值2“的行指数”和值“密钥2”存储到一个变量。然后使用该“包含value2的行的索引”,我将该行的“第一个TD”(或者如果有三个TD,获得第三个TD)更改为“changed key”之类的东西?

类似于“tr的索引”,然后指定“td的索引”来改变...不知道这是可能的jQuery或JavaScript。

回答

1

如果传递的jQuery一个td,你可以得到它的指数是一个包含行(相对于其他行)与$(obj).parents("tr").index(); //obj is the td object passed in 可以在同一台做表格单元格:如果你知道 $("#yourtable td").eq(index).text("Your Value"); //index is the index you wanna grab

8

该行和单元格的指数,你可以做这样的事情:

$(document).ready(function(){ 
    $('#someTable tr:nth-child(2) td:nth-child(1)').html('foo'); 
}); 

您也可以拉使用相同的选择单元格的当前值,但.html()而不是.html(content)

Fiddle here

0
//First, obtain the td that contains 'Value2' 
var $tdThatContainsValue2 = $("#someTable tr td").filter(function(){ 
    return $(this).html() == "Value 2"; 
}); 
//Then, obtain the first td in its row (it's first 'sibling'); 
$firstCellOfValue2row = $tdThatContainsValue2.siblings("td").eq(0); 
alert($firstCellOfValue2row.html()); //Will show "Key 2" 

希望这有助于

相关问题