2017-06-14 64 views
0

我想要獲得連續的所有td的寬度的數組。首先,我得到的所有td的陣列:jquery:獲得連續寬度的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();}); 

但只是返回一個空數組。

如何獲得寬度數組?

+1

你的map函數中的對象'the_data'不是一個jQuery對象,你試過這個$(the_data)嗎? –

+0

@ÁngelB。這工作!如果你把它作爲答案,我會標記它正確 – Philip7899

回答

1

對象在你的地圖功能「the_data」不是一個jQuery對象,你必須添加一個jQuery選擇得到一個jQuery對象:

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

然後你可以訪問jQuery的width()方法。

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 
}); 
+0

爲什麼你不想使用'map'?你基本上在上面的代碼中實現你自己的'map'版本。 – maddockst

+0

看來,OP不清楚如何使用地圖,所以我提供了一個替代方案,他們可能會更舒適。 「each」的語法大致是黑白的,在這種使用情況下,性能差異完全可以忽略不計。如果OP在「map」上設置,他們可以跳過我的答案並找到他們更喜歡的一個。 – Santi

0

你是不是爲$.map回調中返回任何東西。你需要返回函數內部的寬度像這樣:

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