我正在尝试根据一系列货币格式的数字创建一个小计,但我正在努力将数字转换回整数以便可以添加它们。以下是我的尝试:
$(function() {
var totals = $('.price');
var sum = 0;
for (var i = 0; i < totals.length; i++) {
//strip out dollar signs and commas
$(totals[i].text()).replace(/[^\d.]/g, '');
//convert string to integer
var ct = parseFloat($(totals[i].text()));
sum += ct;
}
console.log(sum);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$195,000.20</div>
<div class="price">$21,404.00</div>
<div class="price">$7,000.00</div>
<div class="price">$450.00</div>
&#13;
答案 0 :(得分:2)
replace()
不会修改传入的字符串(无论如何它都不能在这里,因为它是函数的结果)。它只是返回修改后的值。
保存replace()
的结果,并根据该结果汇总:
$(function() {
var totals = $('.price');
var sum = 0;
for (var i = 0; i < totals.length; i++) {
//strip out dollar signs and commas
var v = $(totals[i]).text().replace(/[^\d.]/g, '');
//convert string to integer
var ct = parseFloat(v);
sum += ct;
}
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$195,000.20</div>
<div class="price">$21,404.00</div>
<div class="price">$7,000.00</div>
<div class="price">$450.00</div>
另外:请注意拼写错误 - 您需要$(totals[i]).text()
,而不是$(totals[i].text())