开发者

min / max functionality in jQuery

开发者 https://www.devze.com 2023-03-11 15:40 出处:网络
How would you find using jQuery an element with maximal \"page\" value which is less than \"6\" ? Suppose that \"page\" has only numerical values, and that the elements are sorted by \"page\". For ex

How would you find using jQuery an element with maximal "page" value which is less than "6" ?

Suppose that "page" has only numerical values, and that the elements are sorted by "page". For example:

<div id="wrapper">
  <div page="1"></div&开发者_开发百科gt;
  <div page="2"></div>
  <div page="4"></div>      => answer
  <div page="6"></div>
  <div page="7"></div>
  <div page="9"></div>
</div>


You can use filter to select all the selectors less than 6, and then select the last one.

$('#wrapper div').filter(function() {
  return $(this).attr('page') < 6;
}).last().css('color', 'red');

example: http://jsfiddle.net/niklasvh/rFYfM/


Since you didn't (originally) specify whether the list is sorted, I'll assume they're not, in which case you must iterate over all of the elements and record the one that matches:

var maxEl = null;
var maxNum = 0;

$('#wrapper > div').each(function() {
    var num = $(this).attr('page');
    if (num > maxNum && num < 6) {
        maxNum = num;
        maxEl = this;
    }
});

// result is in maxEl

See http://jsfiddle.net/alnitak/WdT2m/ for working demo


This works for unsorted list:

i = 0;
$('div').filter(function(){
    $thispage = $(this).attr('page')
    if($thispage < 6 && $thispage > i){
        i = $thispage;
        return true;
    }
    return false;
}).last()


$("#wrapper > div[page]")
.filter( function() { return parseInt($(this).attr("page")) < 6; } )
.sort( function(a,b) { return parseInt($(a).attr("page")) - parseInt($(b).attr("page")); } )
.last();

Broken down:

  • Grabs all div's immediately within your wrapper that have a page attribute.

  • Filters to include only those elements that are less than 6.

  • Sorts these elements. (can skip this if you know your div's are sorted).

  • Selects the last element found, and thus the element that meets your condition.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号