我需要某种方式来总结跨度中的文本值,但是我只能提取它们而不能总结。有没有办法正确地做到这一点?我对代码不了解,我是jQuery的新手。

演示:http://jsfiddle.net/0L4s6g8p/1/

HTML:

<div class="prices">

    <h3>Option 1 = $<span class="sum" id="option-1">11.11</span></h3>
    <h3>Option 2 = $<span class="sum" id="option-2">22.22</span></h3>
    <h3>Option 3 = $<span class="sum" id="option-3">33.33</span></h3>

</div>

<h3>Subtotal = $<span id="subtotal">0.00</span></h3>


脚本:

$('.prices').each(function(){
      var sum = $('.sum').text();
      $(this).each(function(){
        sum += parseInt($('.sum').text());
      });
      $("#subtotal").text(sum);
    });

最佳答案

您需要遍历每个sum元素并将其累加



var sum = 0;
$('.sum').each(function() {
  sum += +$(this).text()||0;
});
$("#subtotal").text(sum);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="prices">

  <h3>Option 1 = $<span class="sum" id="option-1">11.11</span></h3>
  <h3>Option 2 = $<span class="sum" id="option-2">22.22</span></h3>
  <h3>Option 3 = $<span class="sum" id="option-3">33.33</span></h3>

</div>

<h3>Subtotal = $<span id="subtotal">0.00</span></h3>

关于javascript - jQuery总结跨度中的文本值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27563847/

10-14 13:53