Javascript 在jquery中获取更高值的列表id
我有一份清单:Javascript 在jquery中获取更高值的列表id,javascript,jquery,html-lists,Javascript,Jquery,Html Lists,我有一份清单: <ul id="testList"> <li id="3"></li> <li id="2"></li> <li id="1"></li> </ul> 我希望有人能帮助我。非常感谢你! 问候 可能不是最有效的方法,但这可以做到: // initialize the max value to a low number var max = 0; // iterate over
<ul id="testList">
<li id="3"></li>
<li id="2"></li>
<li id="1"></li>
</ul>
我希望有人能帮助我。非常感谢你!
问候 可能不是最有效的方法,但这可以做到:
// 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');
可能不是最有效的方法,但这可以做到:
// 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');
您可以使用
Math.max
和map()
获得最大id值,然后使用addClass()
var h=Math.max.apply(null,$('#testList li').map(函数(){
返回$(this.attr('id');
}))
$('#'+h).addClass('last')代码>
您可以使用Math.max
和map()
获得最大id值,然后使用addClass()
var h=Math.max.apply(null,$('#testList li').map(函数(){
返回$(this.attr('id');
}))
$('#'+h).addClass('last')代码>
不错。知道有更好的方法,完全忘记了地图。谢谢你们,你们太棒了!我解决了我的问题!;-)美好的知道有更好的方法,完全忘记了地图。谢谢你们,你们太棒了!我解决了我的问题!;-)