使用javascript获取最高ID

时间:2013-03-12 20:07:35

标签: javascript jquery

我有一堆音符div,格式如下:

<div class="note-row" id="1">
<div class="note-row" id="2">
<div class="note-row" id="4">
<div class="note-row" id="5">
<div class="note-row" id="6">

如何使用javascript获取最大的id?到目前为止,我有:

$('.note-row').each(function() {
    ??
});

6 个答案:

答案 0 :(得分:12)

快速而肮脏的方式:

var max = 0;
$('.note-row').each(function() {
    max = Math.max(this.id, max);
});
console.log(max); 

这有点短且更复杂(使用reduce,并允许负值ID降至Number.NEGATIVE_INFINITY,如Blazemonger所建议的那样:

var max = $('.note-row').get().reduce(function(a, b){
    return Math.max(a, b.id)
}, Number.NEGATIVE_INFINITY);

答案 1 :(得分:8)

你可以这样做:

var ids = $('.note-row').map(function() {
    return parseInt(this.id, 10);
}).get();

var max = Math.max.apply(Math, ids);

答案 2 :(得分:2)

有趣但这也有效:

var max = $('.note-row').sort(function(a, b) { return +a.id < +b.id })[0].id;

http://jsfiddle.net/N5zWe/

答案 3 :(得分:2)

为了完整性,优化Vanilla JS解决方案:

var n = document.getElementsByClassName('note-row'),
    m = Number.NEGATIVE_INFINITY,
    i = 0,
    j = n.length;
for (;i<j;i++) {
    m = Math.max(n[i].id,m);
}
console.log(m);

答案 4 :(得分:0)

你找到任何max,loop的方式相同:

var max = -999; // some really low sentinel

$('.note-row').each(function() {
    var idAsNumber = parseInt(this.id, 10);
    if (idAsNumber  > max) {
        max = idAsNumber;
    }
});

答案 5 :(得分:0)

  var maxID = -1;
  $('.note-row').each(function() {
       var myid = parseInt($(this).attr('id'),10);
       if( maxID < myid ) maxID = myid;
  });
  // the value of maxID will be the max from id-s
相关问题