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

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

Consider the following HTML:

相关标签:
6条回答
  • 2020-12-01 21:35
    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]').

    0 讨论(0)
  • 2020-12-01 21:41
    var max =0;
    $('.a').each(function(){
    
        if(parseFloat($(this).attr('x'))>max)
        {
             max = parseFloat($(this).attr('x')) ;
        }
    });
    
    alert(max);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-01 21:44

    You could also use Array.sort in jQuery, as explained here then use $('.a:last') to get the selected element.

    0 讨论(0)
  • 2020-12-01 21:52

    Just loop over them:

    var maximum = null;
    
    $('.a').each(function() {
      var value = parseFloat($(this).attr('x'));
      maximum = (value > maximum) ? value : maximum;
    });
    
    0 讨论(0)
  • 2020-12-01 21:58

    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.

    0 讨论(0)
提交回复
热议问题