Loop through all elements with class 'blah' and find the highest id value

前端 未结 4 2146
闹比i
闹比i 2021-02-13 20:25

I have a bunch of elements like:

..

I want to loop through all of them and get the highest

相关标签:
4条回答
  • 2021-02-13 21:05

    I think you need the second value the splitted ID, and you might want to convert the string to an integer, like this:

    var newid = 0;
    
    $(".blah").each(function() {
    
      var id = parseInt( this.id.split('-')[1], 10 );
    
      if( id > newid)
        newid = id;
    
    });
    
    0 讨论(0)
  • 2021-02-13 21:21

    I would do:

    var max = 0;
    $(".blah").each(function(){
        num = parseInt(this.id.split("-")[1],10);
        if(num > max)
        {
           max = num;
        }
    });
    

    Most people would do this way.

    0 讨论(0)
  • 2021-02-13 21:21

    You want to use parseInt so numerical operators apply

    var id = parseInt($(this).attr('id').split('-')[1]);
    
    0 讨论(0)
  • 2021-02-13 21:25

    I'd go for this, using .map, .get and .sort:

    $('.blah').map(function(){
        return parseInt(this.id.split('-')[1], 10);
    }).get().sort(function(a, b) {
        return b - a;
    })[0];
    
    0 讨论(0)
提交回复
热议问题