jQuery:如何计算所有匹配元素的最大属性值?

时间:2011-09-23 05:20:44

标签: javascript jquery

考虑以下HTML:

<div class="a" x="6"></div>
<div class="a" x="9"></div>
<div class="a" x="2"></div>
...
<div class="a" x="8"></div>

您如何找到所有x元素的最大.a值?

假设所有x值都是正整数。

7 个答案:

答案 0 :(得分:25)

只是循环遍历它们:

var maximum = null;

$('.a').each(function() {
  var value = parseFloat($(this).attr('x'));
  maximum = (value > maximum) ? value : maximum;
});

答案 1 :(得分:9)

我有另一个版本:

var numbers = $(".a").map(function(){
    return parseFloat(this.getAttribute('x')) || -Infinity;
}).toArray();

$("#max").html(Math.max.apply(Math, numbers));

这使用map函数提取x-Attributes的值,将对象转换为数组并将数组元素作为函数参数提供给Math.max

Math.max技巧从http://ejohn.org/blog/fast-javascript-maxmin/

被盗

<强>更新

添加“|| -Infinity”以在没有属性时正确处理案例。见@kubedan的小提琴

答案 2 :(得分:1)

回到现代 javascript 中:

let maxA = $(".a").get().reduce(function (result, item) {
  return Math.max(result, $(item).attr("x"));
}, 0);

答案 3 :(得分:0)

var max = null;

$('.a').each(function() {
  var x = +($(this).attr('x'));
  if (max === null || x > max)
    max = x;
}

alert(max === null ? "No matching elements found" : "The maximum is " + max);

请注意一元+运算符将属性转换为数字。您可能希望添加一些错误检查以确保它实际上 一个数字 - 并且该属性完全存在。您可以将选择器更改为仅选择具有类和属性的元素:$('.a[x]')

答案 4 :(得分:0)

var max =0;
$('.a').each(function(){

    if(parseFloat($(this).attr('x'))>max)
    {
         max = parseFloat($(this).attr('x')) ;
    }
});

alert(max);

答案 5 :(得分:0)

您也可以在jQuery中使用Array.sort,如here所述,然后使用$('。a:last')来获取所选元素。

答案 6 :(得分:0)

我正在对这个主题进行一些测试,如果性能很重要,那么旧的但简单的for优于jQuery.map()Math.apply()Array.sort()

var items = $(".a");
for (var i = 0; i < items.length; i++) {
  var val = items.eq(i).prop('x');
  if (val > max) max = val;
}

以下是 jsperf 测试:http://jsperf.com/max-value-by-data-attribute。没有什么是真正的激烈,但无论如何都很有趣。