找到最大的数字属性

时间:2014-12-16 19:01:44

标签: javascript jquery

如何选择另一个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>    

我想要做的是,找到div具有最大id attribute

id attribute

我使用以下代码来抓取$('.posts .post').data('id');

{{1}}

但是返回最新,而不是最大

3 个答案:

答案 0 :(得分:6)

var max = 0;
$('.post').attr("data-id", function(i,v){
   max = +v > max ? +v : max;
});

console.log( max ); // 5

另一种方式:

var ids = $('.post').map(function(){
   return +this.dataset.id;            // or use jQ: return +$(this).data('id');
});

console.log( Math.max.apply(Math, ids) ); // 5

http://api.jquery.com/jquery.map/用于返回所需值的新数组 How might I find the largest number contained in a JavaScript array?用于其余部分。

一元+用于将任何可能的字符串数转换为Number 要防止NaN导致错误插入Alpha字符导致的不匹配,您可以使用:

return +this.dataset.id || 0; // Prevent NaN and turn "a" to 0

答案 1 :(得分:2)

如果您喜欢underscore,可以使用max功能完成以下操作。

var getIdAttr = function(el){ return el.getAttribute('data-id'); };
var elementIds = _.map($('.post'), getIdAttr);
var maxId = _.max(elementIds);

console.log(maxId); // 5
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<div class="posts">
  <div class="post" data-id="3"></div>
  <div class="post" data-id="5"></div>
  <div class="post" data-id="1"></div>
  <div class="post" data-id="4"></div>
</div>

答案 2 :(得分:0)

在我看来,比追踪价值和自己进行比较更清洁。只需将值推送到数组并使用Math确定最大值

var max = Math.max.apply(Math, $(".posts .post").map(function () {
    return $(this).data("id");
}));

http://jsfiddle.net/d0wuxygs/

供参考:Get max and min value from array in JavaScript