简体   繁体   English

获取使用jQuery或js指定行的表的文本值

[英]Get text value of a table specifying a row with jQuery or js

I want to get data of a table row by row to create a string with the data separated by comma. 我想逐行获取表的数据,以创建一个字符串,并用逗号分隔数据。 The table looks like this: 该表如下所示:

在此处输入图片说明

I want to have a string with data from table separated by comma (CSV style) as follows: 我想要一个字符串,其中的数据来自表,以逗号分隔(CSV样式),如下所示:

myText = Consistently exceeds requirements- Benchmark, 1, Exceeds some requirements, 1, Meets requirements, 2, myText =始终超出要求-基准1,超出某些要求1,满足要求2,

The table HTML looks like this: 表格HTML如下所示:

在此处输入图片说明

I tried the following code but I have not been able to get the value/text of only one row, then ask for next cell in the same row, then jump to next one. 我尝试了以下代码,但我无法仅获取一行的值/文本,然后在同一行中请求下一个单元格,然后跳至下一行。

console.log($('.sm-data-table-summary').eq(2).text());

But it retrieves all table data for second element found in the whole page. 但是它将检索整个页面中第二个元素的所有表数据。

csv_string += ($('.sm-data-table-summary > tbody').prop("innerText") + ',');

But it gets all data for the table, meaning option text + percentage + numeric value and goes thru all options, not giving me the option to separate with commas 但这会获取表的所有数据,这意味着选项文本+百分比+数值,并遍历所有选项,而没有给我选项以逗号分隔

$(element).find('.sm-data-table-summary').each(function() {
            console.log($(this).find("tr:nth-child(2)").text());
        });

This last one is closest I am to what I want, I got the 2nd text, percentage and numeric value for each table found in the page. 最后一个是我最想要的,我在页面中找到每个表的第二个文本,百分比和数字值。 Again all at once not giving me chance to separate by comma. 再一次,所有这些都没有给我机会以逗号分隔。

Do you know a way to get only the option text, then the percentage, then the numeric value of the same row? 您知道一种只获取选项文本,百分比,然后是同一行的数值的方法吗? And then move to next row? 然后移到下一行?

Or maybe is the wrong approach. 也许是错误的方法。

See if this works: 查看是否可行:

 var els = $(".sm-data-table-summary").find(".label,.sm-data-total").get(); var myText = els.map(function(e) { return $(e).text(); }).join(","); // debugging console.log("texts:", myText); document.body.innerHTML += myText; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="sm-data-table-summary" border=1> <tr> <td><div class="label">a-label</div></td> <td>a-percent</td> <td><div class="sm-data-total">a-1</div></td> </tr> <tr> <td><div class="label">b-label</div></td> <td>b-percent</td> <td><div class="sm-data-total">b-1</div></td> </tr> </table> <hr> 

As you can see, this only gets the label and sm-data-total of each row. 如您所见,这仅获取每行的labelsm-data-total If you want the percentage, all you have to do is change the argument to the .find() . 如果需要百分比,则只需将参数更改为.find()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM