【问题标题】:Getting third cell of each row获取每行的第三个单元格
【发布时间】:2012-08-12 04:33:26
【问题描述】:
var Rows = $("#tableid tbody tr");
Rows.each(function(index, element) {
var thirdCell = $(this+":nth-child(3)").text();
alert(thirdCell);
});
var thirdCell 行中的某些内容无法正常工作。每行有四个孩子,都是 td 标签。我想获取第三个单元格中的文本。
【问题讨论】:
标签:
javascript
jquery
html-table
tablerow
【解决方案1】:
试试下面的方法,
var Rows = $("#tableid tbody tr");
Rows.each(function(index, element) {
var thirdCell = $(this).find('td').eq(2).text();
alert(thirdCell);
});
【解决方案2】:
this 不是字符串,它是一个 jquery 对象,因此在构建新选择器时不能附加它。你可以这样做:
var selector = $(this).selector;
var thirdCell = $(selector+":nth-child(3)").text();
alert(thirdCell);
http://jsfiddle.net/2URV7/
【解决方案3】:
这不起作用,因为 tr 没有文本。它有 TD。您可以通过 html() 应用来获取 tr 的 innerHTML,或者在 tds 上使用 text() 如果它们实际上包含文本。
【解决方案4】:
您可以通过基于 0 的索引从每一行获取所有单元格
Rows.each(function(index, element) {
var thirdCell = $(this.cells[2]).text();
alert(thirdCell);
});
或者你可以在原始选择器中获取它
var Third = $("#tableid tbody tr > td:nth-child(3)");
Third.each(function(index, element) {
var thirdCell = $(this).text();
alert(thirdCell);
});