如何使用 javascript 返回数据属性数组

How to return an array of data attributes using javascript?

本文关键字:数据属性 数组 返回 javascript 何使用      更新时间:2023-09-26

请原谅我糟糕的JavaScript知识。

我正在尝试从标记为"选定"的 DOM 元素返回一个 ID 值数组,例如 [1,2,4]。

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

这似乎只返回最后一个元素的数据 id 值。

如何创建所有 ID 值的数组?

尝试

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

演示

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

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

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

好吧,你也可以使用.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