简体   繁体   中英

How to push element attribute value into javascript array?

This is my html structure. Here, i have created two attributes for each element. How to push attribute value into an array (like this structure, [[1,0],[1,1],[1,2],[0,2],[2,2],[1,3],[1,4]])?

<div id="demo">
     <div data-floor="1" data-floor-sub="0">Div1</div>
     <div data-floor="2" data-floor-sub="0">Div2</div>
     <div data-floor="3" data-floor-sub="0">Div3</div>
     <div data-floor="3" data-floor-sub="1">Div4</div>
     <div data-floor="3" data-floor-sub="2">Div5</div>
     <div data-floor="4" data-floor-sub="0">Div6</div>
     <div data-floor="5" data-floor-sub="0">Div7</div>
</div> 

Use map()

 var multiDimArray = $('#demo div').map(function() { var innerArray = []; innerArray.push([$(this).data('floor'), $(this).data('floor-sub')]); return innerArray; }).get(); console.log(multiDimArray); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div id="demo"> <div data-floor="1" data-floor-sub="0">Div1</div> <div data-floor="2" data-floor-sub="0">Div2</div> <div data-floor="3" data-floor-sub="0">Div3</div> <div data-floor="3" data-floor-sub="1">Div4</div> <div data-floor="3" data-floor-sub="2">Div5</div> <div data-floor="4" data-floor-sub="0">Div6</div> <div data-floor="5" data-floor-sub="0">Div7</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM