如何使用 JQuery 或 Javascript 连续更改特定 TD 的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5825844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:05:09  来源:igfitidea点击:

How to change value of a particular TD in a row with JQuery or Javascript?

javascriptjqueryhtml

提问by Tesselate

So if I have table:

所以如果我有桌子:

<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>

Is there a way I can get the "index of the row" of value 2 and store the value "Key2" into a variable. Then using that "index of the row containing value2", I change the "first TD"(or if there were three TD's, get the 3rd TD) of that row to something like "changed key"?

有没有办法可以获取值 2 的“行索引”并将值“Key2”存储到变量中。然后使用“包含 value2 的行的索引”,我将该行的“第一个 TD”(或者如果有三个 TD,则获取第三个 TD)更改为“更改的键”之类的内容?

Something like "index of tr" and then specifying "index of td" to change... not sure if that is possible with jquery or javascript.

诸如“tr 索引”之类的东西,然后指定“td 索引”进行更改……不确定 jquery 或 javascript 是否可行。

回答by Demian Brecht

If you know the index of the row and cell, you could do something like this:

如果您知道行和单元格的索引,您可以执行以下操作:

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

You can also pull the current value of the cell using the same selector, but .html()rather than .html(content)

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

Fiddle here

在这里摆弄

回答by Thomas Shields

If you pass jQuery a td, you can get the index of it's containing row (relative to the other rows) with $(obj).parents("tr").index(); //obj is the td object passed inYou can do the same to the table cell: $("#yourtable td").eq(index).text("Your Value"); //index is the index you wanna grab

如果您传递 jQuery a 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

回答by Edgar Villegas Alvarado

//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"

Hope this helps

希望这可以帮助