使用 javascript 从行中添加总计

Add total from rows using javascript

我想在下面的 table 中添加总值,但有一些我不知道如何实现的条件

<table id="tableID" width="200" border="1">
  <tr>
    <td class="compulsory">5</td>
    <td class="compulsory">8</td>
    <td class="compulsory">8</td>

    <td class="one">8</td>
    <td class="one">7</td>
    <td class="one">6</td>

    <td class="two">9</td>
    <td class="two">4</td>

    <td class="total"></td>
  </tr>
</table>

条件是;

Table data with class compulsory must be added

Table data with class one pick the highest two values

Table data with class two pick the highest one value

然后用classtotal

显示Table数据中的合计

这是一个使用 jQuery 的解决方案:

var total = 0,
    oneVal = 0,
    twoVal = 0,
    one = [],
    two = [],
    $tds = $('td:not(:last-child)');

$tds.each(function(i) {
    var currentClass = $(this).attr('class'),
        currentVal = parseInt($(this).html());
  
    switch (currentClass) {        
        case 'one':
            one.push(currentVal);
            break;

        case 'two':
            two.push(currentVal);
            break;
        
        default:
          total += currentVal;
    }

    if (i + 1 === $tds.length) {
        // Sort and sum the big ones
        one.sort(function(a, b) { return a - b });
        oneVal = one[one.length - 1] + one[one.length - 2];

        // Get the max
        twoVal = Math.max.apply(Math, two);
          
        total = total + oneVal + twoVal;
    } 
});

$('td.total').html(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="tableID" width="200" border="1">
  <tr>
    <td class="compulsory">5</td>
    <td class="compulsory">8</td>
    <td class="compulsory">8</td>

    <td class="one">8</td>
    <td class="one">7</td>
    <td class="one">6</td>

    <td class="two">9</td>
    <td class="two">4</td>

    <td class="total"></td>
  </tr>
</table>

@Yosel 代码的问题在于他对所有值求和。你的条件是求和第一组的所有值,第二组的前2个和第三组的最高值。

这将产生总共 45 个。

使用 jQuery 会容易得多,但是问题被标记为 JavaScript,所以我添加了一个仅 JS 的解决方案。

首先使用 querySelectorAll 查询集合的所有元素。初始化一个总和变量,它将跟踪总数。

第一组很简单,我们可以将所有项目加在一起。由于 HTML 集合无法访问所有数组方法,因此我们需要创建单独的数组来存储值。

在您的示例中,值的排序很方便,但我们不能总是假设情况就是这样。 运行 sort 函数以防万一。要获得前两个值,可以使用 slice 函数。

迭代我们刚刚找到的最大的两个数字并将值添加到我们的总和中。第三个更简单一些,因为我们可以使用 max 函数

var table = document.getElementById("tableID");

/* we have three seperate groups. Because each has a different condition, we have to create three separate variables.*/
var compulsory = document.querySelectorAll(".compulsory");
var one = document.querySelectorAll(".one");
var two = document.querySelectorAll(".two");

var sum = 0;                     // Store the running total

for (var i = 0; i < compulsory.length; i++) {
    sum += parseInt(compulsory[i].innerHTML);
}

/* QuerySelectorAll returns a collection, so we can't use the sort method on it. Have to create new array objects. */
var oneValues = []; var twoValues = [];

for (var i = 0; i < one.length; i++) {
    oneValues.push(parseInt(one[i].innerHTML));
}

/* Can't assume numbers will always be in order. Sort by descending first and then take the first two numbers */
oneValues = oneValues.sort((a,b) => b - a).slice(0,2);

// Sum up these two numbers;
for (var i = 0; i < oneValues.length; i++) {
    sum += oneValues[i];
}

for (var i = 0; i < two.length; i++) {
    twoValues.push(parseInt(two[i].innerHTML));
}

sum += Math.max.apply(Math, twoValues);

document.getElementsByClassName("total")[0].innerHTML = sum;
td {
  padding: 5px;
}

.total {
  font-weight: bold;
}
<table id="tableID" width="200" border="1">
  <tr>
    <td>Compulsory</td>
    <td class="compulsory">5</td>
    <td class="compulsory">8</td>
    <td class="compulsory">8</td>

    <td>One</td>
    <td class="one">8</td>
    <td class="one">7</td>
    <td class="one">6</td>

    <td>Two</td>
    <td class="two">9</td>
    <td class="two">4</td>
     <td>Total</td>
    <td class="total"></td>
  </tr>
</table>

下面的解决方案如何,如果需要,您可以进一步重构。

<html>
<body>
    <table border="1" id="tableID" width="200">
        <tr>
            <td class="compulsory">5</td>
            <td class="compulsory">8</td>
            <td class="compulsory">8</td>
            <td class="one">8</td>
            <td class="one">7</td>
            <td class="one">6</td>
            <td class="two">9</td>
            <td class="two">4</td>
            <td class="total"></td>
        </tr>
    </table>
</body>
<script type="text/javascript">
var table = document.getElementById('tableID');
var tr = table.getElementsByTagName('tr')[0];
var tdsCompulsory = tr.getElementsByClassName('compulsory');
var tdsOne = document.getElementsByClassName('one');
var tdsTwo = document.getElementsByClassName('two');

var cData = [];
var oneData = [];
var twoData = [];
var sum = 0;

for(var i in tdsCompulsory){
    if(typeof tdsCompulsory[i].textContent != 'undefined')
    cData.push(tdsCompulsory[i].textContent);
}
for(var i in tdsOne){
    if(typeof tdsOne[i].textContent != 'undefined')
    oneData.push(tdsOne[i].textContent);
}
for(var i in tdsTwo){
    if(typeof tdsTwo[i].textContent != 'undefined')
    twoData.push(tdsTwo[i].textContent);
}
console.log(cData);
console.log(oneData);
console.log(twoData);

for(var i in cData){
    sum +=parseInt(cData[i]);
}

var maxOne=0, maxTwo=0;
for(var i in oneData){
        if(maxOne < parseInt(oneData[i])){
            maxTwo = maxOne;
            maxOne = parseInt(oneData[i]);
        } else if(maxTwo < parseInt(oneData[i])){
            maxTwo = parseInt(oneData[i]);
        }
}
sum += maxOne + maxTwo;

var max = 0;
for(var i in twoData){
    if(max < parseInt(twoData[i])){
        max = parseInt(twoData[i]);
    }
}
console.log(max);    
sum +=max;
console.log(sum);    
document.getElementsByClassName('total')[0].textContent = sum;
</script>
</html>