簡體   English   中英

獲取所有匹配元素的數據屬性?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM