简体   繁体   English

如何获得父div中子代的总和?

[英]How do I get the sum of children within a parent div?

I'm attempting to add the sum of children within a parent div, but haven't been able to limit the scope of the math to children of a single parent. 我正在尝试在父div中添加子项的总和,但无法将数学范围限制为单亲子项。

I'm starting with an array: 我从一个数组开始:

[
  {
    "item1-name": "item1",
    "item1-price": "$100.00",
    "item2-name": "item2",
    "item2-price": "$200.00",
    "item3-name": "item3",
    "item3-price": "300.00",
    "item4-name": "item4",
    "item4-price": "$400.00",
    "total": "$1,000.00"
  },
  {
    "item1-name": "item1",
    "item1-price": "$100.00",
    "item2-name": "item2",
    "item2-price": "$200.00",
    "item3-name": "item3",
    "item3-price": "300.00",
    "item4-name": "",
    "item4-price": "",
    "total": "$0.00"
  },
  {
    "item1-name": "item1",
    "item1-price": "$100.00",
    "item2-name": "item2",
    "item2-price": "$200.00",
    "item3-name": "",
    "item3-price": "",
    "item4-name": "",
    "item4-price": "",
    "total": "0"
  }
]

Then I write the contents of the page into html with javascript 然后我用javascript将页面内容写成html

function values(row){
  return '<div class="container">' +
    '<p>' + row["item1-name"] + '<span class="value  cost">' +  
    row["item1-price"] + '</span></p>' +
    '<p>' + row["item2-name"] + '<span class="value  cost">' + 
    row["item2-price"] + '</span></p>' +
    '<p>' + row["item3-name"] + '<span class="value  cost">' + 
    row["item3-price"] + '</span></p>' +
    '<p>' + row["item4-name"] + '<span class="value  cost">' + 
    row["item4-price"] + '</span></p>' +
    '<h4>Total' + '<span class="value  total">' + row["total"] + 
    '</span></h4>' +
  '</div>';
 };

 var containers = document.getElementsByClassName("container");

 function findTotals(container){
 $.each(containers, function(){
    var sum = 0;

     $(this).children(".cost").each(function() {
         var val = $.trim( $(this).text() );

         if ( val ) {
             val = parseFloat( val.replace( /^\$/, "" ) );
             sum += !isNaN( val ) ? val : 0;
         }
      });
      alert(sum);
   });
  };

function buildRows(rows){
   var allRows = "";
   rows.forEach(function(row){
   allRows = allRows + admitTemplate(row);
   })

   document.getElementById('rowHolder').innerHTML = allRows;
   findTotals();
}

fetch('queryExport.json')
  .then(response => {
    if (response.ok){
    return response.json()
  } else {
     return Promise.reject('something went wrong!')
  }
})
.then(rows => {
  buildRows(rows);
})

.catch(error => console.log('error is', error));

The problem lies in the findTotals function. 问题出在findTotals函数中。 I want to limit the sum to the .cost values inside each .container div. 我想将总和限制为每个.container div中的.cost值。 (currently the total comes to 1900, when the totals are 1000, 600, 300. (all the .cost values on the page are being added, when I'm really trying to iterate over one .container div at a time, executing the function within the scope of the parent (.container) div. (当前总数为1900,当总数为1000、600、300时。)(当我真的想一次遍历一个.container div时,执行页面上的所有.cost值。父(.container)div范围内的函数。

You can see the totals are broken. 您可以看到总数已破。 My next goal will be to compare the sums to the total value. 我的下一个目标是将总和与总价值进行比较。 If they don't match, I'll highlight the broken total value, so the query generating it can be fixed. 如果它们不匹配,我将突出显示损坏的总值,因此可以修复生成它的查询。

Thank you for you for your guidance. 感谢您的指导。

您永远不会重置sum的值,因此循环的每次迭代都会添加到现有值,而不是独立的。

The issue is in your selector and DOM construction: $(this).children. 问题出在选择器和DOM构造中:$(this).children。 Children looks for all the DOM elements that are children, not all descendants. 子代查找所有子代的DOM元素,而不是所有子代。 .cost is not a child element of .container, it is a child element of p. .cost不是.container的子元素,它是p的子元素。 If you replace it with .find, you will get the results. 如果将其替换为.find,则会得到结果。

 function findTotals(container) { $.each(containers, function() { var sum = 0; $(this).find(".cost").each(function() { var val = $.trim($(this).text()); if (val) { val = parseFloat(val.replace(/^\\$/, "")); sum += !isNaN(val) ? val : 0; } }); console.log(sum); }); }; 

Here's a link to a fiddle that works as well - https://jsfiddle.net/z5oug908/1/ 这是一个同样有效的小提琴的链接-https: //jsfiddle.net/z5oug908/1/

Updated Answer 更新的答案

So the more I thought about this, the more I wondered if you really need to be searching the DOM to do a sum of the totals. 因此,我考虑的越多,我越想知道您是否真的需要搜索DOM来求和。 You have all the data you need in an array already. 您已经在阵列中拥有了所需的所有数据。 We can use map, filter and reduce to calculate the totals before you ever render them like this: 我们可以使用map,filter和reduce来计算总计,然后再像这样渲染它们:

 function calculateTotals(rows) { return rows.map(row => { const rowTotal = Object.keys(row).filter(key => { const match = key.search(/(price)/gi) return match !== -1; }).reduce((pre, cur) => { let val = row[cur]; val = parseFloat(val.replace(/^\\$/, "")); if (val) { return val + pre; } return pre; }, 0); row["total"] = rowTotal; return row; }) } 

A completed example that should work: 一个完整的示例应该可以工作:

 function calculateTotals(rows) { return rows.map(row => { const rowTotal = Object.keys(row).filter(key => { const match = key.search(/(price)/gi) return match !== -1; }).reduce((pre, cur) => { let val = row[cur]; val = parseFloat(val.replace(/^\\$/, "")); if (val) { return val + pre; } return pre; }, 0); row["total"] = rowTotal; return row; }) } function admitTemplate(row) { return '<div class="container">' + '<p>' + row["item1-name"] + '<span class="value cost">' + row["item1-price"] + '</span></p>' + '<p>' + row["item2-name"] + '<span class="value cost">' + row["item2-price"] + '</span></p>' + '<p>' + row["item3-name"] + '<span class="value cost">' + row["item3-price"] + '</span></p>' + '<p>' + row["item4-name"] + '<span class="value cost">' + row["item4-price"] + '</span></p>' + '<h4>Total' + '<span class="value total">' + row["total"] + '</span></h4>' + '</div>'; }; function buildRows(rows) { var allRows = ""; rows.forEach(function(row) { allRows = allRows + admitTemplate(row); }) document.getElementById('rowHolder').innerHTML = allRows; } fetch('queryExport.json') .then(response => { if (response.ok) { return response.json() } else { return Promise.reject('something went wrong!') } }) .then(calculateTotals) .then(buildRows); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM