使用jQuery从td单元格中获取文本

Getting text from td cells with jQuery

本文关键字:获取 取文本 单元格 td jQuery 使用      更新时间:2023-09-26

我在jQuery中有以下代码:

children('table').children('tbody').children('tr').children('td')

获取每行的所有表单元格。我的问题是:我如何才能在每行中的每个单元格中获得文本值?

我应该使用.each()来遍历所有children('td')吗?如何获取每个td的文本值

首先,你的选择器是多余的。我建议使用类或ID选择器,就像下面的例子一样。一旦修改了选择器,只需使用jQuery的.each()来遍历集合:

ID选择符:

$('#mytable td').each(function() {
    var cellText = $(this).html();    
});

类选择器:

$('.myTableClass td').each(function() {
    var cellText = $(this).html();    
});

附加信息:

看一下jQuery的选择器文档

您可以使用.map: http://jsfiddle.net/9ndcL/1/。

// array of text of each td
var texts = $("td").map(function() {
    return $(this).text();
});

我会给你的tds一个特定的类,例如data-cell,然后使用这样的东西:

$("td.data-cell").each(function () {
    // 'this' is now the raw td DOM element
    var txt = $(this).html();
});
$(document).ready(function() {
  $('td').on('click', function() {
    var value = $this.text();
  });
});
$(".field-group_name").each(function() {
        console.log($(this).text());
    });