Jquery:连续获取td' s的宽度数组

时间:2017-06-14 21:29:16

标签: javascript jquery dom

我正在尝试连续获取所有td的宽度数组。首先,我得到所有td的数组:

datas = $('.totals').prev().find("tr").last().find("td");

然后测试我正确使用$.map方法,我输出每个元素:

$.map(datas, function(the_data){console.log(the_data)});

上面的代码返回:

<td class="col col-name">18</td>
<td class="col col-1">1</td>
<td class="col col-2">2</td>
<td class="col col-3">0</td>
<td class="col col-4">3</td>
<td class="col col-5">3%</td>

我现在尝试运行$.map方法来收集所有td的宽度:

$.map(datas, function(the_data){the_data.width();});

上面的代码返回:

VM4255:1 Uncaught TypeError: the_data.width is not a function
    at <anonymous>:1:42
    at Function.map (jquery.self-bd7ddd3….js?body=1:485)
    at <anonymous>:1:3

我也尝试过:

$.map(datas, function(){$(this).width();});

但只返回一个空数组。

如何获得宽度数组?

3 个答案:

答案 0 :(得分:1)

对象&#39; the_data&#39;在你的map函数中不是一个jQuery对象,你必须添加一个jQuery选择器来获取一个jQuery对象:

$.map(datas, function(the_data){$(the_data).width();});

然后你可以访问jQuery width()方法。

答案 1 :(得分:0)

如果您只想尝试获取宽度数组,则可以完全避免使用map

var widths = [];
datas = $('.totals').prev().find("tr").last().find("td");

datas.each(function() {             //iterate through each cell
    widths.push($(this).width());   //add its width to the array
});

答案 2 :(得分:0)

你没有在$.map的回调中返回任何内容。您需要返回函数内部的宽度,如下所示:

$.map(datas, function(){return $(this).width();});