gpt4 book ai didi

javascript - 计算父 div 内的所有数字,然后按总计对它们进行排序

转载 作者:行者123 更新时间:2023-11-28 01:08:58 24 4
gpt4 key购买 nike

我想计算内部所有“计数”的每个“行计数”的总数,然后根据“行总计”对“行”进行排序。但总数将 class="count"的所有数字相加,而不是仅将其父级“行计数”内的数字相加。

<div id="container">
<div class="row">
<div class="row-counts">
<span class="count">12</span>
<span class="count">4</span>
<span class="count">5</span>
<span class="count">7</span>
</div>
<div class="row-totals">

</div>
</div>
<div class="row">
<div class="row-counts">
<span class="count">4</span>
<span class="count">66</span>
<span class="count">0</span>
<span class="count">12</span>
</div>
<div class="row-totals">

</div>
</div>
<div class="row">
<div class="row-counts">
<span class="count">7</span>
<span class="count">99</span>
<span class="count">42</span>
<span class="count">17</span>
</div>
<div class="row-totals">

</div>
</div>
</div>

<script>
// to calculate sum of all numbers in .row-counts
$('.row-counts').each(function(){
var sum = 0;
var select = $(this).find('.count');
select.each(function()
{
sum += parseFloat($(this).text());

});
$('.row-totals').html(sum);
});

// to sort on .row-totals
$(".row-totals").orderBy(function() {return +$(this).text();}).appendTo("#container");

jQuery.fn.orderBy = function(keySelector)
{
return this.sort(function(a,b)
{
a = keySelector.apply(a);
b = keySelector.apply(b);
if (a > b)
return 1;
if (a < b)
return -1;
return 0;
});
};
</script>

排序插件来自此主题:Sorting divs by number inside div tag and jQuery

最佳答案

给你。代码注释了一些指针。希望这可以帮助。 http://jsfiddle.net/N5Sd2/

// to calculate sum of all numbers in .row-counts
$('.row').each(function(index,RowElement){ // For each row

var thisRowTotal = $(RowElement).find('.row-totals'); // set output div in variable
var thisRowCounts = $(RowElement).find('.row-counts'); // set row count parent div in variable
var sum = 0; // create sum var

thisRowCounts.each(function(i,RowCountParent){ // for each row count parent

var select = $(RowCountParent).find('.count'); // find counts
select.each(function(i,e){ // for each count found
sum = sum + parseInt($(e).html()); // convert into integer and add to sum
}); // when finished
thisRowTotal.html(sum); // output sum to output div
});

});

// to sort on .row-totals

jQuery.fn.orderBy = function(keySelector) // MAKE SURE YOU INIT THE PLUGIN...
{
return this.sort(function(a,b)
{
a = keySelector.apply(a);
b = keySelector.apply(b);
if (a > b)
return 1;
if (a < b)
return -1;
return 0;
});
};

// ....BEFORE YOU CALL IT IN YOUR CODE! This line moved UNDER the plugin.
$(".row-totals").orderBy(function() {return +$(this).text();}).appendTo("#container");

关于javascript - 计算父 div 内的所有数字,然后按总计对它们进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24709287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com