[英]Get data attribute for all matched elements?
假设我有如下所示的HTML:
<div class="test" data-file="1"></div>
<div class="test" data-file="2"></div>
我想获取所有数据文件值的列表。 我尝试使用$(.test).data("file")
但这仅返回1
,这根据jQuery的文档是有意义的,该文档指出它将返回...the value at the named data store for the first element in the set of matched elements.
强调first
。
有没有办法告诉jQuery将所有数据值拉入数组?
当然! 使用.map
var dataValues = $(".test[data-file]").map(function() {
return $(this).data("file");
}).get();
小提琴: http : //jsfiddle.net/5muq33of/
您可以为此创建临时数组:
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.