[英]Acess the table data <td> row by row <tr> individually
I need to make changes to the DOM. 我需要对DOM进行更改。 I need to present the table content using paragaraphs or something like that. 我需要使用文字或类似的东西来呈现表内容。 For that I need to get the data per each row of table. 为此,我需要获取表的每一行的数据。 How can I do this? 我怎样才能做到这一点?
HTML example: HTML示例:
<table style="width:300px">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Output should be something like this - Jill Smith 50
and Eve Jackson 94
输出应该是这样的Jill Smith 50
和Eve Jackson 94
I have written something like this, but it goes through all the <td>
tags in the web page. 我已经写过类似的内容,但是它遍历了网页中的所有<td>
标签。 Not row wise. 不是明智的。
$("table").each(function() {
$("tr").each(function(){
$("td").each(function(){
label = $('td').text();
});
alert(label);
});
Try, 尝试,
var groupedVales = [];
$('table tr').each(function(){
groupedVales[groupedVales.length] =
$(this).find('td').map(function(){ $(this).text(); }).get().join(' ');
});
Now the groupedvales
contains elements which will be grouped as per your expectations 现在, groupedvales
包含将根据您的期望进行分组的元素
try, 尝试,
FLAG = true;
text2 = "";
$("table tr").each(function(){
text1="";
$(this).find('td').each(function(){
text1 += $(this).text() + " ";
});
if(FLAG)
{
text2=text1+" "+"and"+" "
FLAG=false;
}
else
{
text2+=text1
}
});
alert(text2);
$('table tr').each(function () {
$('body').append($(this).text() + "<br/>");
alert($(this).text());
});
Iterate through each <tr>
.text()
property... 遍历每个<tr>
.text()
属性...
Give an ID to the table (for instance: mytable) and then do something like this: 给该表一个ID(例如:mytable),然后执行以下操作:
$("#mytable").find("tr").each(function () {
var rowtext = "";
$(this).find("td").each(function () {
rowtext += $(this).text() + " ";
});
});
Why the ID? 为什么要输入ID? ID selectors are faster than element selectors and ensures the code runs only for the table you want, if you want the same code to run on multiple tables a class selector would be ideal. ID选择器比元素选择器要快,并且可以确保代码仅在所需的表上运行,如果您希望同一代码在多个表上运行,则选择器是理想的选择。
Why not $("#mytable tr")? 为什么不使用$(“#mytable tr”)? jquery reads the selectors right to left, this means that jquery would first find every "tr" element in the document and then filter by wether they have a parent with the id "mytable". jquery从右到左读取选择器,这意味着jquery将首先找到文档中的每个“ tr”元素,然后筛选它们是否具有ID为“ mytable”的父级。 Separating the selectors like this: $("#mytable").find("tr") ensures jquery only selects "tr" elements inside the element with "mytable" id. 像这样分隔选择器:$(“#mytable”)。find(“ tr”)确保jquery仅选择ID为“ mytable”的元素内的“ tr”元素。
This is another solution. 这是另一种解决方案。 You can try! 你可以试试!
$('table tr').each(function(i,e){
temp=[];
$(this).find('td').each(function(){
temp.push($(this).text());
});
resultBlock.append('"' + temp.join(' ') + '"');
if($(this).index()!=($('table tr').length-1)) resultBlock.append(' and ');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.