[英]Get data attribute for all matched elements?
Say I have HTML like below: 假设我有如下所示的HTML:
<div class="test" data-file="1"></div>
<div class="test" data-file="2"></div>
I would like to get a list of all the data-file values. 我想获取所有数据文件值的列表。 I tried using,
$(.test).data("file")
but this only returns 1
which makes sense according to jQuery's documentation which states it will return ...the value at the named data store for the first element in the set of matched elements.
我尝试使用
$(.test).data("file")
但这仅返回1
,这根据jQuery的文档是有意义的,该文档指出它将返回...the value at the named data store for the first element in the set of matched elements.
Emphasis on first
. 强调
first
。
Is there any way to tell jQuery to pull all of the data values into an array? 有没有办法告诉jQuery将所有数据值拉入数组?
Of course! 当然! Use
.map
使用
.map
var dataValues = $(".test[data-file]").map(function() {
return $(this).data("file");
}).get();
Fiddle: http://jsfiddle.net/5muq33of/ 小提琴: http : //jsfiddle.net/5muq33of/
You can create temporary array for that purpose: 您可以为此创建临时数组:
var myArray = [];
$('.test').each( function() {
myArray.push( $( this ).data( 'file' ) );
});
console.log( myArray );
var dataValues = $(".test[data-file]").map(function() { return $(this).data("file"); }).get(); console.log(dataValues);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="test" data-file="1"></div> <div class="test" data-file="2"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.