简体   繁体   English

返回First值的数组 <td> 每个 <tr> 的 <tbody>

[英]Return an Array of values of First <td> in Each <tr> of <tbody>

I am trying to return an array of values for the first <td> of every <tr> within <tbody> of my table. 我正在尝试为表的<tbody>中每个<tr>的第一个<td>返回一个值数组。

A demo here (attempt, not working) http://jsfiddle.net/vJqeT/1/ 这里的演示 (尝试,不起作用) http://jsfiddle.net/vJqeT/1/

My JS Code: 我的JS代码:

var newArray = $('#table1 tr:first td').map(function() {
    return $(this).html();
});

My expected result in my demo is: 我在演示中的预期结果是:

[A, 1] [A,1]

target all TR's, and then all TD's that are the first child of a TR, then get the trimmed text : 定位所有TR,然后定位所有TR的第一个孩子的TD,然后获取修剪后的文本:

var newArray = $.map($('#table1 tr td:first-child'), function (el) {
    return $.trim( $(el).text() );
});

FIDDLE 小提琴

A few things ( fiddle ): 一些事情( 小提琴 ):

  1. You've targeted tr:first so any subsequent rows are ignored. 您已将tr:first目标,因此所有后续行都将被忽略。
  2. You should be targeting cells rather than rows . 您应该针对单元格而不是
  3. jQuery's :first selector is easily confused with :first-child . jQuery的:first选择器很容易与:first-child混淆。 Unfortunately, :first returns only one item. 不幸的是, :first只返回一个项目。 Use :first-child instead. 使用:first-child代替。
  4. Call toArray() so you get a plain array. 调用toArray()以便获得纯数组。
var newArray = $('#table1 td:first-child span').map(function () {
    return $(this).html();
}).toArray();

console.log(newArray);

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

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