获取jquery和ecmascript6

时间:2018-04-26 13:52:39

标签: javascript jquery ecmascript-6 arrow-functions

尝试获取具有相同数据属性的所有选择的最大值。但收到错误

  

{“message”:“Uncaught TypeError:undefined不是函数”,
  “filename”:“https://stacksnippets.net/js”,“lineno”:37,“colno”:   34}

请在下面运行代码段我希望它可以控制3,因为这是最高的responsegroupnumber,其中question.id为1

$(document).ready(function() {
  let question = {
    Id: 1
  };

  let responseGroupNumber = Math.max(...$(`select[data-questionid = ${question.Id}]`)
    .map(x => $(x)
      .attr('data-responsegroupnumber')));

  console.log(responseGroupNumber);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select data-questionid="1" data-responsegroupnumber="1">
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>


<select data-questionid="1" data-responsegroupnumber="2">
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>

<select data-questionid="1" data-responsegroupnumber="3">
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>

2 个答案:

答案 0 :(得分:3)

您需要在映射之前使用jQuery .get()函数:

如果不这样做,您将使用jQuery .map()方法而不是Array#map

$(document).ready(function() {
  let question = {
    Id: 1
  };
  
  let responseGroupNumber = Math.max(...$(`select[data-questionid = ${question.Id}]`).get().map(x => $(x).attr('data-responsegroupnumber')));
  console.log(responseGroupNumber);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select data-questionid="1" data-responsegroupnumber="1">
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>


<select data-questionid="1" data-responsegroupnumber="2">
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>

<select data-questionid="1" data-responsegroupnumber="3">
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>

答案 1 :(得分:0)

另一种可能的实现方式是:

$(document).ready(function() {
 let question = {
   Id: 1
 };

 var selects = $(`select[data-questionid=${question.Id}]`).toArray();
 var dataGroupNumber = selects.map(select => ($(select).attr('data- 
   responsegroupnumber')));

let responseGroupNumber = Math.max.apply(null, dataGroupNumber);
console.log(responseGroupNumber);
});

Math.max.apply(null,dataGroupNumber)而不是将数组扩展到Math.max(...)中;