如何使用 jQuery 和 JavaScript 选择一行中的特定列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3622543/
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 05:27:47  来源:igfitidea点击:

How can I select a specific column in a row using jQuery and JavaScript?

javascriptjqueryjquery-selectors

提问by swati

I am very new to jQuery and JavaScript. I have a small question. Let's say i have a HTML table like the following

我对 jQuery 和 JavaScript 很陌生。我有一个小问题。假设我有一个如下所示的 HTML 表格

<Table id="mytable">
 <tr id="element">
  <td>value</td>
  <td>text</td>
</tr>
</Table>

In the above example i know the row id and i want to change the value of the second column of the row with that particular id.

在上面的示例中,我知道行 id,我想更改具有该特定 id 的行的第二列的值。

I need a result something like the following:

我需要一个类似于以下的结果:

 <Table id="mytable">
 <tr id="element">
  <td>value</td>
  <td>ChangedText</td>
</tr>
</Table>

So my question is: how can I select the 2ndcolumn of the first row with a given id in order to change the value?

所以我的问题是:如何选择具有给定 id 的第一行的第二列以更改值?

回答by Gert Grenander

$("#element td:nth-child(2)").text('ChangedText');

Here's an example.

这是一个例子

回答by Yanick Rochon

something like

就像是

$('#mytable tr:eq(0) td:eq(1)').text('ChangedText');

will select the first row, second column (0 based) of the given element (TABLE). In your case, since you know the row id :

将选择给定元素 (TABLE) 的第一行、第二列(基于 0)。在您的情况下,因为您知道行 id :

$('#mytable #element td:eq(1)').text('ChangedText');

or simply

或者干脆

$('#element td:eq(1)').text('ChangedText');

回答by JoeChin

Gert's code is how I would have implemented what you are asking so I won't repost it. However since you are new to jquery/javascript, you might like this tool I use to make sure my selectors are working http://www.woods.iki.fi/interactive-jquery-tester.html.

Gert 的代码是我如何实现你所要求的,所以我不会重新发布它。但是,由于您是 jquery/javascript 的新手,您可能会喜欢我用来确保选择器正常工作的这个工具http://www.woods.iki.fi/interactive-jquery-tester.html

Cheers, Joe

干杯,乔