如何将元素属性值推入javascript数组?

时间:2015-08-02 05:52:34

标签: javascript jquery

这是我的html结构。在这里,我为每个元素创建了两个属性。如何将属性值推入数组(如此结构,[[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> 

1 个答案:

答案 0 :(得分:3)

使用map()

&#13;
&#13;
var multiDimArray = $('#demo div').map(function() {
  var innerArray = [];
  innerArray.push([$(this).data('floor'), $(this).data('floor-sub')]);
  return innerArray;
}).get();

console.log(multiDimArray);
&#13;
<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>
&#13;
&#13;
&#13;