Javascript 使用 jQuery 从 td 单元格中获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8325655/
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
Getting text from td cells with jQuery
提问by Vlad
I have this code in jQuery:
我在 jQuery 中有这个代码:
children('table').children('tbody').children('tr').children('td')
Which gets all table cells for each row. My question is: how can I get the text value in each cell in each row?
它获取每行的所有表格单元格。我的问题是:如何获取每行每个单元格中的文本值?
Should I use .each()
to loop trough all children('td')
? How can I get the text value of each td
?
我应该.each()
用来循环遍历所有children('td')
吗?如何获取每个的文本值td
?
回答by James Hill
First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each()to iterate through the collection:
首先,你的选择器是矫枉过正的。我建议使用类或 ID 选择器,如下例所示。一旦你更正了你的选择器,只需使用 jQuery 的.each()来遍历集合:
ID Selector:
ID选择器:
$('#mytable td').each(function() {
var cellText = $(this).html();
});
Class Selector:
类选择器:
$('.myTableClass td').each(function() {
var cellText = $(this).html();
});
Additional Information:
附加信息:
Take a look at jQuery's selector docs.
看一看jQuery 的选择器文档。
回答by pimvdb
You can use .map
: http://jsfiddle.net/9ndcL/1/.
您可以使用.map
:http: //jsfiddle.net/9ndcL/1/。
// array of text of each td
var texts = $("td").map(function() {
return $(this).text();
});
回答by jabclab
I would give your tds a specific class, e.g. data-cell, and then use something like this:
我会给你的 tds 一个特定的类,例如data-cell,然后使用这样的东西:
$("td.data-cell").each(function () {
// 'this' is now the raw td DOM element
var txt = $(this).html();
});
回答by Love Kumar
$(document).ready(function() {
$('td').on('click', function() {
var value = $this.text();
});
});
回答by Rajan Mandanka
$(".field-group_name").each(function() {
console.log($(this).text());
});