简体   繁体   中英

jQuery: How to calculate the maximal attribute value of all matched elements?

Consider the following 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>

How would you find the maximal x value of all .a elements ?

Assume that all x values are positive integers.

Just loop over them:

var maximum = null;

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

I got another version:

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

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

This uses the map function to extract the values of the x-Attributes, converts the object into an array and provides the array elements as function parameters to Math.max

The Math.max trick was stolen from http://ejohn.org/blog/fast-javascript-maxmin/

UPDATE

add "|| -Infinity" to process the case correctly, when no attribute is present. See fiddle of @kubedan

Coming back to this with modern javascript:

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

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

I was doing some tests regarding this topic, and if performance matters, a old but gold simple for would be better than jQuery.map() , Math.apply() and also 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;
}

Here are the jsperf tests: http://jsperf.com/max-value-by-data-attribute . Nothing really drastic, but interesting anyway.

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);

Note the unary + operator to convert the attribute to a number. You may want to add some error checking to ensure it actually is a number - and that the attribute exists at all. You could change the selector to only select elements with the class and the attribute: $('.a[x]') .

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

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

alert(max);

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