簡體   English   中英

使用jQuery在屬性中找到最小值和最大值

[英]find minimum and maximum value in attribute using jquery

我需要在數據屬性中找到最小值和最大值,但它返回0

這是我的代碼

<div data-price="2" class="maindiv">test</div>
<div data-price="5" class="maindiv">test</div>
<div data-price="3" class="maindiv">test</div>
<div data-price="0" class="maindiv">test</div> 
<div data-price="25" class="maindiv">test</div>     
<div data-price="10" class="maindiv">test</div> 

<script>
    var ids = $("div[data-price]").map(function() {
        return this.id;
    }).get();

    var highest = Math.max.apply( Math, ids );
    var lowest = Math.min.apply( Math, ids );

    alert(highest);
    alert(lowest);
</script>

您需要返回data-price屬性,而不是其ID

 var ids = $("div[data-price]").map(function() { return $(this).attr("data-price"); }).get(); var highest = Math.max.apply( Math, ids ); var lowest = Math.min.apply( Math, ids ); alert(highest); alert(lowest); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-price="2" class="maindiv">test</div> <div data-price="5" class="maindiv">test</div> <div data-price="3" class="maindiv">test</div> <div data-price="0" class="maindiv">test</div> <div data-price="25"class="maindiv">test</div> <div data-price="10" class="maindiv">test</div> 

您可以使用常規JavaScript執行此操作:

 //Variable to hold our results var data = []; //Loop through HTML nodes for (var i = 0; i < document.querySelectorAll(".maindiv").length; i++) { data.push({ node : document.querySelectorAll(".maindiv")[i], value : parseInt(document.querySelectorAll(".maindiv")[i].getAttribute("data-price")) }); } //Sort lowest to highest (Only use one sort! Pick either this or the next one as they overwrite each Other) data = data.sort(function (a, b) { return a.value - b.value; }); //Sort highest to lowest (Only use one sort! Pick either this or the last one as they overwrite each Other) data = data.sort(function (a, b) { return b.value - a.value; }); //List all console.log(data); //List first (highest or lowest depending or sort) console.log('first', data[0].value); //List last (highest or lowest depending or sort) console.log('last', data[data.length-1].value); 
 <div data-price="2" class="maindiv">test</div> <div data-price="5" class="maindiv">test</div> <div data-price="3" class="maindiv">test</div> <div data-price="0" class="maindiv">test</div> <div data-price="25" class="maindiv">test</div> <div data-price="10" class="maindiv">test</div> 

當前,您正在從map函數返回id屬性。 將其更改為data-price

var ids = $("div[data-price]").map(function() {
  return $(this).data("price");
}).get();
var highest = Math.max.apply( Math, ids );
var lowest = Math.min.apply( Math, ids );
alert(highest)
alert(lowest)

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM