如何选择另一个div中的所有div并找到最大的id属性?
请考虑以下代码:
<div class="posts">
<div class="post" data-id="5"></div>
<div class="post" data-id="3"></div>
<div class="post" data-id="1"></div>
<div class="post" data-id="4"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我想要做的是,发现div那是最大的id attribute
我使用以下代码来获取id attribute:
$('.posts .post').data('id');
Run Code Online (Sandbox Code Playgroud)
但这会返回最新的,而不是最大的.
var max = 0;
$('.post').attr("data-id", function(i,v){
max = +v > max ? +v : max;
});
console.log( max ); // 5
Run Code Online (Sandbox Code Playgroud)
其他方式:
var ids = $('.post').map(function(){
return +this.dataset.id; // or use jQ: return +$(this).data('id');
});
console.log( Math.max.apply(Math, ids) ); // 5
Run Code Online (Sandbox Code Playgroud)
http://api.jquery.com/jquery.map/用于返回所需值的新数组.
我怎样才能找到JavaScript数组中包含的最大数字?用于其余部分.
一元+用于将任何可能的字符串数转换为Number.
为了防止NaN错误插入的Alpha字符导致的不匹配,您可以使用:
return +this.dataset.id || 0; // Prevent NaN and turn "a" to 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |