2

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">

idjavascriptを使用して最大のものを取得するにはどうすればよいですか?これまでのところ:

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

6 に答える 6

16

迅速で汚い方法:

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

これは少し短く、より洗練されています(Blazemongerによって提案されているように、を使用しreduce、負のIDをまで許可するため):Number.NEGATIVE_INFINITY

var max = $('.note-row').get().reduce(function(a, b){
    return Math.max(a, b.id)
}, Number.NEGATIVE_INFINITY);
于 2013-03-12T20:10:29.503 に答える
8

あなたはこのようなことをすることができます:

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

var max = Math.max.apply(Math, ids);
于 2013-03-12T20:10:47.933 に答える
2

おかしいですが、これも機能します:

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

http://jsfiddle.net/N5zWe/

于 2013-03-12T20:19:22.877 に答える
2

完全を期すために、最適化されたVanillaJSソリューションは次のとおりです。

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);
于 2013-03-12T20:44:36.623 に答える
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;
    }
});
于 2013-03-12T20:11:51.493 に答える
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
于 2013-03-12T20:12:37.257 に答える