我正在尝试使用javascript添加额外费用以计算用户在将商品和运费加在一起时的总费用,但是我得到的所有内容都是NaN为什么?这是我的代码的fiddle
$("#country").change(function() {
var shipping_cost = parseFloat($("#shipping").text().replace(pattern, ''));
var total = parseFloat($("#goods").text().replace(pattern, ''));
var pattern = /[^0-9.-]+/g;
var result = total + shipping_cost;
console.log(result);
if($(this).val() == "17") {
$("#shipping").text("£0.00");
$("#full_price").text("£"+result);
} else {
$("#shipping").text("£5.00");
$("#full_price").text("£"+result);
}
});
<select id="country">
<option value=17>Option 1</option>
<option value=18>Option 2</option>
<option value=19>Option 3</option>
</select>
<p id=goods>£5.00</p>
<p id=shipping>£0.00<p>
答案 0 :(得分:7)
你的模式声明应该在你的解析之前,如下:
var pattern = /[^0-9.-]+/g;
var shipping_cost = parseFloat($("#shipping").text().replace(pattern, ''));
var total = parseFloat($("#goods").text().replace(pattern, ''));
答案 1 :(得分:4)
向上移动var pattern = /[^0-9.-]+/g;
,一切都应该正常工作:
var pattern = /[^0-9.-]+/g;
var shipping_cost = parseFloat($("#shipping").text().replace(pattern, ''));
var total = parseFloat($("#goods").text().replace(pattern, ''));