知道为什么我尝试一起计算的总数是 1.00 吗?
$(document).ready(function() {
// Hide initial values that need updating
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").hide();
// get current delivery rate
$("#get_rate").trigger('click');
// set a timeout and get total and shipping that was generated and add together for nnew total
setTimeout(function() {
// get cart sub-total
var a = $(".cart-total span").html().replace(/[$£]/gi, "");
var ib = $("#estimated-shipping em").html().replace(/[$£]/gi, "");
if (ib == "FREE") {
$("#estimated-shipping em").html("FREE");
var b = "0.00";
} else {
var b = parseFloat($("#estimated-shipping em").text().replace(/\$|£/gi, ""));
}
// add together sub-total and estimated shipping to new total
// update with new total with sub-total and added shipping
var total = parseFloat(a) + parseFloat(b);
total = parseFloat(Math.round(total * 100) / 100).toFixed(2);
$('.cart-finalTotal span').text("£" + total);
// show new values
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").show();
}, 2000);
$(".item-quantity input").on("change", function() {
document.location.href = location.href
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="cart-right">
<p class="cart-total">Sub-Total<span class="money">£1,245.00</span>
</p>
<p class="cart-vat">VAT 20% (included)<span class="money" style="display: block;">£249.00</span>
</p>
<p class="cart-delivery">Delivery (estimated)<span class="money" id="estimated-shipping">+ <em style="display: inline;">FREE</em></span>
</p>
<p class="cart-finalTotal">Total<span class="money" style="display: block;">£0.00</span>
</p>
</div>
最佳答案
在小计中,有一个逗号,当 parseFloat 看到不是点的非数字字符时,它会停止。因此解析 float 返回 1 而不是 1245。您需要您的正则表达式更多地类似于/[^0-9.]/g。
这是有效的代码:
$(document).ready(function() {
// Hide initial values that need updating
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").hide();
// get current delivery rate
$("#get_rate").trigger('click');
// set a timeout and get total and shipping that was generated and add together for nnew total
setTimeout(function() {
// get cart sub-total
var a = $(".cart-total span").html().replace(/[^0-9.]/gi, "");
if ($("#estimated-shipping em").text() == "FREE") {
$("#estimated-shipping em").html("FREE");
var b = "0.00";
} else {
var b = parseFloat($("#estimated-shipping em").text().replace(/[^0-9.]/gi, ""));
}
// add together sub-total and estimated shipping to new total
// update with new total with sub-total and added shipping
var total = parseFloat(a) + parseFloat(b);
total = parseFloat(Math.round(total * 100) / 100).toFixed(2);
$('.cart-finalTotal span').text("£" + total);
// show new values
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").show();
}, 2000);
$(".item-quantity input").on("change", function() {
document.location.href = location.href
});
});
关于javascript - jQuery 计算两个值错误,不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36097421/