2013-10-02 17 views
1

請原諒我可憐的JavaScript知識。如何使用JavaScript返回數組屬性?

我試圖返回一個ID值的數組,例如[1,2,4],來自標記爲「已選」的DOM元素。

<tr data-selected = 'true' data-id = '1'></tr> 
<tr data-selected = 'true' data-id = '2'></tr> 
<tr data-selected = 'false' data-id = '3'></tr> 
<tr data-selected = 'true' data-id = '4'></tr> 

我在此

elems = $("tr[data-selected ='true']").data("id")  
alert(elems) 

創建的CoffeeScript功能嘗試這似乎只返回值最後一個元素的數據-ID。如何創建所有ID值的數組?

+0

BTW問題並不都jQuery的標籤,但在看片段用我假設它是jQuery的只有... – PSL

回答

7

嘗試

$('tr[data-selected="true"]').map(function(){ 
    return $(this).data('id'); 
}).get(); 

Demo

當您使用返回多個項目選擇ATTR /數據,它會給你只從第一個匹配元素的結果。因此,使用.map獲取特定的數據屬性值並將其轉換爲jquery對象集合中的數組。

原因在於實施.attr/data的方式。

// Gets 
bulk ? 
    fn.call(elems) : 
    length ? fn(elems[0], key) : emptyGet; //<-- snippet from jquery just considers the first element. 
+0

感謝,就是我在找的東西。並且一個非常有用的解釋 –

+0

@AndyHarvey不客氣地... – PSL

0

那麼你也.each功能

$(document).ready(function(){ 
    var ids = []; 
    elems = $("tr[data-selected=true]").each(function(){ 
    ids.push($(this).attr('data-id')); 
    }); 
console.log(ids); 
}) 

<tr data-selected = 'true' data-id = '1'></tr> 
<tr data-selected = 'true' data-id = '2'></tr> 
<tr data-selected = 'false' data-id = '3'></tr> 

http://jsbin.com/iqEYAPI/1/edit

+1

不應該使用'每個'將一個集合變成另一個集合;這就是'map'的用途。 – meagar