How can I select a specific column in a row using

2019-02-16 09:53发布

问题:

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

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

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 2nd column of the first row with a given id in order to change the value?

回答1:

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

Here's an example.



回答2:

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 :

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

or simply

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


回答3:

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.

Cheers, Joe