循环遍历所有带有'blah'类的元素并找到最高的id值

Bla*_*man 12 jquery

我有一堆元素,如:

<div id="car-123" class="blah">..</div>
Run Code Online (Sandbox Code Playgroud)

我想循环遍历所有这些并获得最高ID,即123

这该怎么做?

以下是正确的,最好的方法吗?

$(".blah").each(function() {

   var id = $(this).attr('id').split('-')[0];

   if( id > newid)
      newid = id;

});
Run Code Online (Sandbox Code Playgroud)

Rob*_*itt 17

我会做:

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

大多数人会这样做.


lon*_*day 10

我会去,使用.map,.get.sort:

$('.blah').map(function(){
    return parseInt(this.id.split('-')[1], 10);
}).get().sort(function(a, b) {
    return b - a;
})[0];
Run Code Online (Sandbox Code Playgroud)


Joh*_*tta 1

您想使用parseInt数字运算符,因此适用

var id = parseInt($(this).attr('id').split('-')[1]);
Run Code Online (Sandbox Code Playgroud)