如何将Class添加到具有最大数据属性值的div?

时间:2015-01-06 03:58:18

标签: javascript jquery

如何从数据属性中找到最大或最小的值,并将一个类添加到具有最大或最小找到值的div中?

HTML输出:

<div data-foo="12"></div>
<div data-foo="43"></div>
<div data-foo="3"></div>
<div data-foo="44"></div>
<div data-foo="153" class="yellow"></div>

.addClass(&#34;黄色&#34);

我发现这个stackoverflow问题确实有助于找到最大值或最小值,但是如何将类应用于此值来自的div?

Get the highest and lowest values of a certain attribute in jQuery or Javascript

3 个答案:

答案 0 :(得分:8)

试试这个:

<强> SCRIPT:

<script>
    $(document).ready(function(){
    var max = 0;
    $('div').attr("data-foo", function(i,val){
       max = +val > max ? +val : max;
    });
   $("div[data-foo='" + max + "']").addClass("yellow");// this is what you need to add class.do same process for min also if you required.
    console.log(max);
//for min 

var min = max;
    $('div').attr("data-foo", function(i,v){
       min = +v < min ? +v : min;
    });
    $("div[data-foo='" + min + "']").addClass("red");
}); 

<强> HTML:

<div data-foo="12"></div>
<div data-foo="43"></div>
<div data-foo="3"></div>
<div data-foo="44"></div>
<div data-foo="153"></div>

答案 1 :(得分:0)

&#13;
&#13;
function minMaxId(selector) {
  var min = null,
    max = null;
  $(selector).each(function() {
    var id = parseInt($(this).data('foo'), 10);
    if ((min === null) || (id < min)) {
      min = id;
    }
    if ((max === null) || (id > max)) {
      max = id;
    }
  });
  return {
    min: min,
    max: max
  };
}

// Returns Obj with min and max
minMaxId('div'); // => {min:1, max:5}

// Set a span with the values
$('#tmpMin').html(minMaxId('div').min)
$('#tmpMax').html(minMaxId('div').max)

// Change the highest one to have the class yellow
$('[data-foo=' + minMaxId('div').max + ']').addClass('yellow')

// Change the lowest one to have the class grey
$('[data-foo=' + minMaxId('div').min + ']').addClass('grey')
&#13;
.yellow {
  background: yellow;
  }

.grey {
  background: grey;
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-foo="12">Div 1</div>
<div data-foo="43">Div 2</div>
<div data-foo="3">Div 3</div>
<div data-foo="44">Div 4</div>
<div data-foo="153">Div 5</div>

Min: <span id="tmpMin"></span> || Max: <span id="tmpMax"></span>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

首先,我认为你想要关闭你的DIV标签。 接下来,您可以使用元素的索引来突出显示它,例如

$('div').eq(divIndex).addClass('yellow');

要获取divIndex,您只需遍历列表并执行最小/最大搜索,如下所示:

loop {
  if(curValue > value){
    value = curValue;
  }
}

请参阅jsFiddle上的完整内容:http://jsfiddle.net/pavkr/f2t1a5e2/