Jquery 获取同级的最大id值
下面的代码控制台.log将获得Jquery 获取同级的最大id值,jquery,Jquery,下面的代码控制台.log将获得[0,1,…] 如何知道同级div。a的id值获得最大值 $('.a').hover(function(){ console.log('$('.a')'); },function(){}); html 0 1. 2. 3. 首先,您不应该使用以数字开头的id。它们在HTML5中是正确的,但在许多工具和CSS中存在问题 但是,如果要获取id最大的元素,可以执行以下操作: var me; $('.a').each(function(){ var num
[0,1,…]
如何知道同级div
。a
的id值获得最大值
$('.a').hover(function(){
console.log('$('.a')');
},function(){});
html
0
1.
2.
3.
首先,您不应该使用以数字开头的id。它们在HTML5中是正确的,但在许多工具和CSS中存在问题
但是,如果要获取id最大的元素,可以执行以下操作:
var me;
$('.a').each(function(){
var num = Number(this.id); // this ensures the id is only a number
if (num && !(me && me.id>num)) {
me = this;
}
});
现在假设您的id是“a1”、“a2”等
那你就可以了
var me;
$('.a[id^="a"]').each(function(){
var num = Number(this.id.slice(1));
if (num && !(me && me.id.slice(1)>num)) {
me = this;
}
});
看看这个
var highestVal = parseInt($('.a').first().attr('id'));
$('.a').first().siblings().each(function(index, item){
var crntVal = parseInt($(item).attr('id'));
if (crntVal > highestVal) { highestVal = crntVal; }
});
alert(highestVal);
这是我能想到的最短代码:
var high = Math.max.apply(null, $('.a').map(function(_, el) {
return +el.id;
}));
如果您希望使用数据id
,只需将el.id
替换为$(el.data('id')
)
请注意,此方法不是“数据安全”的,因为在尝试查找最大值之前,它不会对单个值进行清理。如果你在错误的元素上运行它(垃圾输入),你会得到错误的答案(垃圾输出)。不要那样做 我使用了不同的方法,而不是
id
html代码:
<div class="a" data-id="0">0</div>
<div class="a" data-id="30">30</div>
<div class="a" data-id="1">1</div>
<div class="a" data-id="2">2</div>
<div class="a" data-id="3">3</div>
0
30
1.
2.
3.
不相关,但只是我注意到的一些事情,失去
悬停
,使用鼠标悬停,鼠标悬停
,根据WC3,ID不应以开头,或本身是整数。@Ohgodwhy取决于您询问W3C的哪个部分。它在HTML5中是合法的,但在CSS中是不合法的。请了解何时不使用jQuery-$(item).attr('id')==item.id
注意1)这将返回id,而不是似乎是op目标的元素2)一旦其中一个元素没有id或具有非数字id,它就会失败。这很遗憾:Math.max.apply(null,[1,2,NaN])
==>NaN
@dystroy我的理解是他想要“最大的ID”。是的,NaN
与Math.max
有关的问题有点烦人。至于没有id或非数字-这只是垃圾输入垃圾输出的情况。谢谢回复!如果console.log(me)将获得所有html,如何获得最大的id值请参见,我告诉过您他想要的是数字,而不是元素;-)@vibskov最大的数字就是me.id
如果我使用if(num&&!(me&&me.id>num)){me=this;console.log(me.id);}将得到列表中的所有数字
// this var will store the element with the highest ID
var big;
$(".a").each(function() {
if (!big) // if big is not set, assume the first is the highest
big = this;
else
{
// retrieves the `data-id` from the element
// converts to integer and compare, re-assign big if needed
if (parseInt($(this).data("id")) > parseInt($(big).data("id")))
big = this;
}
});
// displays the `data-id` of the element with the highest value
alert($(big).data("id"));
<div class="a" data-id="0">0</div>
<div class="a" data-id="30">30</div>
<div class="a" data-id="1">1</div>
<div class="a" data-id="2">2</div>
<div class="a" data-id="3">3</div>