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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4619278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:35:46  来源:igfitidea点击:

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

jquery

提问by Blankman

I have a bunch of elements like:

我有一堆元素,例如:

<div id="car-123" class="blah">..</div>

I want to loop through all of them and get the highest ID i.e. 123

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

how to do this?

这该怎么做?

Is below correct and the best way?

下面是正确的和最好的方法吗?

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

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

   if( id > newid)
      newid = id;

});

回答by RobertPitt

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.

大多数人都会这样做。

回答by lonesomeday

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

我会这样做,使用.map,.get.sort

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

回答by John Giotta

You want to use parseIntso numerical operators apply

你想使用parseInt所以数字运算符适用

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

回答by Harmen

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

我认为您需要拆分 ID 的第二个值,并且您可能希望将字符串转换为整数,如下所示:

var newid = 0;

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

  var id = parseInt( this.id.split('-')[1], 10 );

  if( id > newid)
    newid = id;

});