简体   繁体   English

在jquery和ecmascript6中获得最高的属性号

[英]get highest attribute number in jquery and ecmascript6

trying to get the max value for all selects with the same data attribute. 尝试获取具有相同数据属性的所有选择的最大值。 but receiving the error 但收到错误

{ "message": "Uncaught TypeError: undefined is not a function", {“ message”:“未捕获的TypeError:未定义不是函数”,
"filename": " https://stacksnippets.net/js ", "lineno": 37, "colno": 34 } “ filename”:“ https://stacksnippets.net/js ”,“ lineno”:37,“ colno”:34}

please run snippet below I would like it to console out 3 as that is the highest responsegroupnumber with a question.id of 1 请在下面运行代码段,我希望它可以调出3,因为这是带有response.id为1的最高responsegroupnumber

 $(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> 

You need to use the jQuery .get() function before mapping : 您需要在映射之前使用jQuery .get()函数:

If you don't, you'll be using jQuery .map() method instead of Array#map 如果不这样做,您将使用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> 

Another possible implementation could be: 另一种可能的实现方式可能是:

$(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) instead of spread the array inside the Math.max( ... ); Math.max.apply(null,dataGroupNumber)而不是在Math.max(...)内部扩展数组;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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