问题
I am trying to get the td values using jQuery for a table I have no control over. There is an excellent example posted on this site, but it references one column not multiple ones within each tr.
I also don't have an id for the table or rows... only a class=columndata
for the td.
$('#mytable tr').each(function() {
var customerId = $(this).find("td").eq(2).html();
}
will get the single td of a fixed tr?
Here is my table data:
<tr valign="top">
<td class="columnaction" valign="center">
<img src="../images/spacer.gif" width="1" height="1" />
<a href="javascript:void(0);" class="columnactionlink" onclick="return doAccept('599577', '1', '','');" alt="Accept">Accept</a>
</td>
<td class="columndata">Message</td>
<td class="columndata">Test</td>
<td class="columndata"></td>
<td class="columndata"></td>
<td class="columndata">04/09/2011 23:59</td>
<td class="columndata">04/09/2011</td>
<td class="columndata">05/12/2011 07:00</td>
<td class="columndata">05/13/2011 07:00</td>
<td class="columndata"></td>
<td class="columndata">Doe, Jeffrey A. (xx)</td>
<td class="columndata">913014405580</td>
<td class="columndata">Skip</td>
<td class="columndata">04/09/2011 16:37</td>
<td class="columndata">C</td>
<td class="columndata">Doe,J</td>
<td class="columndata">04/09/2011 16:37</td>
<td class="columndata">04/09/2011 23:59</td>
<td class="columndata">04/09/2011 16:34</td>
</tr>
Here is the reference to a similar question: How to get a table cell value using jQuery?
回答1:
This is the selector you need:
$('#mytable tbody tr td:nth-child(2)')
回答2:
As @danip pointed out int his statement you can directly access a TD via a valid CSS selector
$('#mytable tbody tr td:nth-child(2)')
a little description what he is doing here
- he selects the table with id=mytable by addressing it with #mytable
- then he goes down to the tbody of the table
- he selects all trs of this table but futher defines
- to select all tds under each tr
- lastly he select from all these tds only the second on for each tr in the table!
you can iterate over the returned dom elements via each like here, and grab the HTML or Textcontent via html() or ()text
$('#mytable tbody tr td:nth-child(2)').each(function() {
output += $(this).text();
});
see this jsfiddle to try it out yourself
http://jsfiddle.net/SdBBy/
Regards
回答3:
Out of the context here but might help you: if you have more than 100 or so rows, the above code will be a bit slower, a 1000 rows and performance will be much slower, in that case you can go with:
$('td:nth-child(2)', '#mytable') //$(selector, context)
and a for loop where you should first cache this object like
var items = $('td:nth-child(2)', '#mytable');
for(var i=0;i<items.length;i++)
{
//your code
}
Regards, SJ
回答4:
use .text()
instead of .html()
.
来源:https://stackoverflow.com/questions/5612128/how-to-get-a-table-cell-value-using-jquery