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

后端 未结 6 838
悲哀的现实
悲哀的现实 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]').

提交回复
热议问题