【问题标题】:Find the greatest Numerical Attribute [duplicate]找到最大的数字属性[重复]
【发布时间】:2015-02-15 04:46:27
【问题描述】:

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

我使用下面的代码来抓取id attribute

$('.posts .post').data('id');

但这会返回最新的,而不是最大的

【问题讨论】:

  • 您在寻找哪个属性? iddata-id?
  • 我当然想要data-id

标签: javascript jquery


【解决方案1】:
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

【讨论】:

  • 谢谢!那行得通。
  • @Akar 不客气
【解决方案2】:

在我看来,这比跟踪价值和自己进行比较更干净。只需将值推送到数组并使用数学来确定最大值。

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

【讨论】:

    【解决方案3】:

    如果你喜欢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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 2019-09-14
      相关资源
      最近更新 更多