Получите сумму внешнегоHeight всех элементов одного класса

Я думаю, что это довольно простая проблема, но...

var outerHeight = $('.profile').outerHeight();
$("#total-height").text(outerHeight + 'px');

Прямо сейчас var outerHeight дает мне внешнийHeight только первого элемента с классом .profile.

Как я могу получить сумму внешнихHeights всех элементов с классом .profile?

Ответы

Ответ 1

Прокрутите каждый соответствующий элемент и добавьте внешние высоты:

var outerHeight = 0;
$('.profile').each(function() {
  outerHeight += $(this).outerHeight();
});
$("#total-height").text(outerHeight + 'px');

Ответ 2

Здесь прямое решение. Просто пропустите элементы объекта jQuery, суммируя outerHeight() s.

var total = 0;
$('.profile').each(function(){
    total += $(this).outerHeight();
});
// total is good here

Важно то, что все получатели jQuery возвращают только значение первого элемента в наборе jQuery, но вы можете добавить их сами.

И вот круговой, но классный способ сделать это http://jsfiddle.net/mendesjuan/bKtAn/6/

// You can use a jQuery object as the `this` param in `Array.prototype` functions
var totalHeight = Array.prototype.reduce.call($('span'), function(a,b){
   // The first param is either the default value (passed into reduce)
   // or the result of the last call of this reducing function
   return a + $(b).outerHeight();
}, 0);

Который может быть обобщен как http://jsfiddle.net/mendesjuan/bKtAn/7/

function addjQValues($jq, getter) {
    return Array.prototype.reduce.call( $jq, function (a, b) {
        return a+ getter.call($(b));
    }, 0);  
}
addjQValues($('span'), $.fn.height)

И превратился в плагин вроде: http://jsfiddle.net/mendesjuan/bKtAn/9/

(function( $ ) {
    $.fn.addUp = function(getter) {  
      return Array.prototype.reduce.call(this, function(a,b){
            return a + getter.call($(b));
      }, 0);  
    }
})(jQuery);
$('span').addUp($.fn.height);
$('span').addUp($.fn.width);
$('span').addUp($.fn.text);

Я думаю, что немного побывал за бортом, извините, я был взволнован, но эти фрагменты кода много рассказывают о JS и даже немного jQuery

Ответ 3

var total = 0;
$('.profile').each(function() {
     total += $(this).outerHeight();
});

$("#total-height").text(total + 'px');

Ответ 4

$("selector") уже является коллекцией. Доступ непосредственно к .outerHeight() или к любому другому методу, например .height()

var total = 0;
$("div").outerHeight(function(i, v){
   total += v;
});

alert( total ); // Just to test

var total = 0;

$("div").outerHeight(function(i, v){ total += v; });

alert( total );
div{background:#eee; margin:3px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:100px;">100px</div>
<div>just lots of breaklines :)<br><br><br><br></div>
<div style="height:200px;">200px</div>

Ответ 5

Функции jQuery, которые не возвращают объект jQuery, работают только с первым членом списка.

Если вы хотите перебрать все элементы .profile, вы можете использовать .each()

var totalHeight = 0;
$('.profile').each(function(i, e) {
    totalHeight += $(e).outerHeight();
});

Ответ 6

Попробуйте следующее:

var outerHeightTotal = 0;
$('.profile').each(function(){
  outerHeightTotal += $(this).outerHeight();
});