代码之家  ›  专栏  ›  技术社区  ›  Shasha

使用Javascript或Jquery获取所有类html内容的总和

  •  0
  • Shasha  · 技术社区  · 6 年前

    我的问题很简单,假设你有多个 <span> 像这样的元素

     <span class="hi">10,000</span>
     <span class="hi">20,000</span>
     <span class="hi">40,000</span>
     <span class="hi">500,000</span>
    

    如何获取span标签中的每个数字内容,去掉逗号并添加数字,获取答案并添加逗号,因为我似乎想不出一种方法来做到这一点。

    这就是我想要实现的

    //数据将从HI类的Span标签中获取

    <script> 
    var addthevalue = 10000+20000+40000+500000;
    $(#theans).html(addthevalue);
    </script>
    
     <div id=theans></div>
    
    4 回复  |  直到 6 年前
        1
  •  4
  •   Nenad Vracar    6 年前

    您可以在上使用spread语法 querySelectorAll 获取一个数组,然后可以使用 reduce 求和的方法。

    const sum = [...document.querySelectorAll('span')].reduce((r, e) => {
      return r + parseInt(e.textContent.replace(',', ''))
    }, 0)
    
    console.log(sum)
    <span class="hi">10,000</span>
    <span class="hi">20,000</span>
    <span class="hi">40,000</span>
    <span class="hi">500,000</span>
        2
  •  2
  •   Cat    6 年前
    var total = 0;
    $(".hi").each(function() {
        total += parseInt($(this).html().replace(",", ""));
    });
    $("#theans").html(total);
    
        3
  •  2
  •   Jeremy Harris    6 年前

    虽然这不是最简洁的方法,但这是一种方法:

    您可以获取元素并使用正则表达式解析任何非数字的内容,然后将其添加到跟踪总和的变量中。

    const elements = document.querySelectorAll('.hi');
    let total = 0;
    elements.forEach((el, i) => {
        const val = el.innerHTML.replace(/[^0-9]/, '');
        total += parseInt(val);
    });
    
    console.log("Total:", total);
     <span class="hi">10,000</span>
     <span class="hi">20,000</span>
     <span class="hi">40,000</span>
     <span class="hi">500,000</span>
        4
  •  2
  •   Tom O.    6 年前

    您可以通过使用正则表达式去掉逗号来轻松做到这一点。一旦你做到了这一点,你基本上只需要总结一下这些值- Array.prototype.reduce 是实现这一目标的简单方法。最后,一旦你有了正确的总和,使用另一个正则表达式函数将其转换为格式正确的逗号字符串。详见代码注释:

    // Util functions
    const stripCommas = s => s.replace(/,/g, ''); // Util function to remove commas from string
    const numberToFormattedString = n => n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    
    // Get the sum as a number
    const sum = Array.from(document.querySelectorAll('.hi')) // Gather an array of DOM elements
      .map(el => Number(stripCommas(el.innerText))) // Strip the commas and turn to Numbers
      .reduce((sum, n) => sum + n, 0); // Sum the numbers using reduce
    
    // Convert the number to a formatted string
    const sumWithCommas = numberToFormattedString(sum);
    
    console.dir(sumWithCommas)
    <span class="hi">10,000</span>
    <span class="hi">20,000</span>
    <span class="hi">40,000</span>
    <span class="hi">500,000</span>

    注: :我得到了密码 numberToFormattedString directly from the accepted answer of this SO question .

        5
  •  2
  •   Yevhen Horbunkov    6 年前

    解决方案的核心是(就像大多数其他答案一样) Array.prototype.reduce() ,但是,由于其他人都忽略了 标签,我会去尝试:

    const total = [...$('.hi')].reduce((sum,span) => sum +=+ $(span).text().replace(/\,/g,''), 0)
    
    $('#sum').text(total)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class="hi">10,000</span>
     <span class="hi">20,000</span>
     <span class="hi">40,000</span>
     <span class="hi">500,000</span>
    <div style="font-weight:bold;">The total is: <span id="sum"></span></div>
        6
  •  2
  •   stjns    6 年前

    试试这个:

     const sum = Array.from(document.getElementsByClassName('hi'))
          .map(el => parseFloat(el.textContent.replace(/[^0-9\.]/g, '')))
          .reduce((total, current) => total + current);
    
    document.getElementById('sum').innerHTML = `sum: ${sum.toLocaleString()}`;
    <span class="hi">10,000</span>
    <span class="hi">20,000</span>
    <span class="hi">40,000</span>
    <span class="hi">500,000.01</span>
    <div id="sum"></div>

    编辑:忘记删除逗号,感谢Jeremy Harris。感谢Yevgen Gorbunkov的性能/功能增强。