2016-10-04 40 views
0

我有一個列表:獲取列表的較高值id jQuery中

<ul id="testList"> 
    <li id="3"></li> 
    <li id="2"></li> 
    <li id="1"></li> 
</ul> 

我需要去使用jQuery li元素的高值id。在這個例子中是3.然後追加類「last」。我試過每個功能,但不工作。

$('#testList li').each(function(index, li){ 

    //Here obtain a higher value id       
    $('#testList li').last().addClass('last');     

}); 

我希望有人能幫助我。非常感謝你! 關心!

回答

2

您可以使用Math.maxmap()獲得價值最大化ID,然後addClass()

var h = Math.max.apply(null, $('#testList li').map(function() { 
 
    return $(this).attr('id'); 
 
})) 
 

 
$('#' + h).addClass('last');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul id="testList"> 
 
    <li id="3"></li> 
 
    <li id="2"></li> 
 
    <li id="1"></li> 
 
</ul>

+1

尼斯。知道有更好的方法,完全忘了'map'。 –

+0

謝謝你們,你太棒了!我解決了我的問題! ;-) – Emily

0

可能不是最有效的方式,但是這將做到這一點:

// initialize the max value to a low number 
var max = 0; 
// iterate over each li item in the list 
$('#testList li').each(function() { 
    // ensure we have a number 
    var id = parseInt($(this).prop('id')); 
    if (! isNaN(id)) { 
     max = Math.max(max, id); 
    } 
}); 

// Given that max contains an ID, just pass that in to the selector to add class 
$('#' + max).addClass('last');