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

后端 未结 6 836
悲哀的现实
悲哀的现实 2020-12-01 20:57

Consider the following HTML:

6条回答
  •  情话喂你
    2020-12-01 21:43

    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

提交回复
热议问题