2011-04-28 30 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" 

希望這有助於

相關問題