获取数据属性的最高值

时间:2016-05-26 06:26:05

标签: javascript jquery html

我的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>
&#13;
&#13;
&#13;

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

4 个答案:

答案 0 :(得分:0)

试试这个

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);

答案 1 :(得分:0)

使用 map() get() 生成data-xdata-y值的值数组。然后使用 Math.min Math.max apply() 一起从数组中获取最大值和最小值。< / p>

&#13;
&#13;
// 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)
)
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以对data-y

应用相同的内容

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

试试这个

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/