簡體   English   中英

獲取數據屬性的最大值

[英]Get the highest values of a data attribute

我的html看起來像

 <div id="container"> <div class="right" data-x="1" data-y="1" ></div> <div class="right" data-x="2" data-y="1" ></div> <div class="right" data-x="3" data-y="1" ></div> <div class="right" data-x="4" data-y="1" ></div> </div> 

如何使用jQuery獲取data-x / data-y的最大值/最小值?

嘗試這個

var containerChilds = document.getElementById("container").children;
var max = 0;
for ( var counter =0; counter < containerChilds.length; counter++)
{
  var value = containerChilds[counter].getAttribute("data-x");
  if ( max < value )
  {
    max = value;
  }
}
console.log(max);

在jQuery中

var max = 0;
$("#container div.right[data-x]").each(function(){
   var value = $(this).attr("data-x");
   max = max < value ? value : max;
});
console.log(max);

使用map()get()生成data-xdata-y值的數組。 然后將Math.minMath.maxapply()一起使用,以從數組中獲取最大值和最小值。

 // generate array of `data-x` attribute var arr1 = $('[data-x]').map(function() { return $(this).data('x'); }).get(); // generate array of `data-y` attribute var arr2 = $('[data-y]').map(function() { return $(this).data('y'); }).get(); console.log( Math.min.apply(Math, arr1), Math.min.apply(Math, arr2), Math.max.apply(Math, arr1), Math.max.apply(Math, arr2) ) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container"> <div class="right" data-x="1" data-y="1"></div> <div class="right" data-x="2" data-y="1"></div> <div class="right" data-x="3" data-y="1"></div> <div class="right" data-x="4" data-y="1"></div> </div> 

您可以對data-y應用相同的內容

 var arrDataX=new Array(); var arrDataY=new Array(); $('div.right').each(function(index){ arrDataX.push($(this).attr("data-x")); arrDataY.push($(this).attr("data-y")); }); var minValue=arrDataX.sort()[0]; var maxValue=arrDataX.sort()[arrDataX.length-1]; alert("Min - "+minValue+", Max - "+maxValue); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div class="right" data-x="1" data-y="1" ></div> <div class="right" data-x="2" data-y="1" ></div> <div class="right" data-x="3" data-y="1" ></div> <div class="right" data-x="4" data-y="1" ></div> </div> 

嘗試這個

var all = $("#container").find(".right");
var max_x =0;
var max_y =0;
var min_x =1;
var min_y =1;
$.each(all,function(k,v){
  if(max_x<$(v).attr("data-x"))
      max_x = $(v).attr("data-x");
  if(min_x>$(v).attr("data-x"))    
     min_x = $(v).attr("data-x");

  if(max_y<$(v).attr("data-y"))
    max_y = $(v).attr("data-y");
  if(min_y>$(v).attr("data-y"))    
     min_y = $(v).attr("data-y");   
})

alert("max_x:"+max_x+" max_y:"+max_y+" min_x:"+min_x+" min_y:"+min_y);

https://jsfiddle.net/sum1/L94ugfyp/

暫無
暫無

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

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