1

Please excuse my poor javascript knowledge.

I'm trying to return an array of ID values, e.g. [1,2,4], from DOM elements that are marked 'selected'.

<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>

My attempt at creating a coffeescript function for this

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

This appears to only return the data-id value of the last element.

How do I create an array of all ID values?

4

2 回答 2

8

尝试

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

演示

当您在返回多个项目的选择器上使用 attr/data 时,它只会为您提供第一个匹配元素的结果。因此使用.map获取特定的 dat 属性值并从 jquery 对象集合转换为数组。

原因在于.attr/data实施的方式。

// Gets
bulk ?
    fn.call( elems ) :
    length ? fn( elems[0], key ) : emptyGet; //<-- snippet from jquery just considers the first element.
于 2013-10-02T01:49:26.597 回答
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

于 2013-10-02T01:52:51.840 回答