jquery map和each 获取dom元素最大值

2011-12-29 00:00:00 by 【6yang】, 1105 visits, 收藏 | 返回

<!DOCTYPE html>
<html>
<head>
  <style>
div { width: 40px; float:left; }
input { clear:left}
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
 

<input type="button" value="equalize div heights">

<div style="background:red; height: 40px; ">1</div>
<div style="background:green; height: 70px;">2</div>
<div style="background:blue; height: 50px; ">3</div>


<script>
$.fn.equalizeHeights = function(){
    var that = this,
        arrHeight = [];
/*    this.each(function(i, n){
        arrHeight.push($(n).height());
        //alert($(n).html())
        //alert(document.getElementsByTagName(n)[i].innerHTML)   
    });*/
    var arrHeight = this.map(function(i, n){
        return $(n).height();
        //alert($(n).html())
        //alert(document.getElementsByTagName(n)[i].innerHTML)   
    }).get();
    var maxheight = function(arr){
        var maxValue;
        for( var i=0, len = arr.length; i < len; i++){
            if(i > 0 && arr[i] > arr[i-1]){
                maxValue = arr[i];
            }
        }
        return maxValue;
    };
   
    that.css({"height": maxheight(arrHeight)});
    //    that.css({"height":  Math.max.apply(this, arrHeight) });
     
};
 
$("input").click(function(){
  $("div").equalizeHeights();
});

</script>

</body>
</html>

分享到:
share

    图片原图

    loading

    loading