我是javascript的新手,我正在尝试在javascript中为我的网站(杯形蛋糕店网站)创建一个简单的价格计算器。首先,我让用户从风味选择列表中选择并将其发布到textarea,当用户选择纯素风味时,我会在发布到textarea时添加$ 3.50到最后,当用户选择非素食时,价格是2.75美元。发布到textarea的所有内容都是字符串。所以对于计算器,我提取最后5个字符(这是价格)并将它们相加以得到小计。我使用循环通过textarea中的列表逐个提取数字并将它们相加,但计算结果出错了。谁能告诉我它有什么问题?
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
function addOption_list(selectbox){
var flavors = new Array("blueberry vegan","butterscotch","cappuccino vegan","carrot
cake","carrot vegan","chocolate walnut vegan",
"chocolate peanut butter vegan","green tea & chocolate","keylime","lavender
vegan","lemon","lemon cream vegan","mandarin orange",
"mint chocolate","mocha","peanut butter & double chocolate","raspberry swirl","red
velvet","sesame","sesame oreo",
"strawberry","strawberry 2 vegan","tangerine","thia tea","triple
chocolate","vanilla","very berry","vietnamese coffee","yuzu");
for (var i=0; i < flavors.length;++i){
addOption(document.drop_list.flavors_list, flavors[i], flavors[i]);
}
}
var $ = function (id){
return document.getElementById(id);
}
var cart = [];
var update_cart = function(){
if(cart.length == 0){
$("flavor_name").value = "";
} else{
var list = "";
for(var i in cart){
list += (parseInt(i) +1) + ". " + cart[i] + /*": $3.50" + */ "\n";
}
$("flavor_name").value = list;
var sum = 0;
for(var i = 0; i < cart.length; i++){
var price = parseFloat(list.substring(list.length - 5));
sum += parseFloat( price.toFixed(2) );
}
$("subtotal").value = sum;
var tax = parseFloat(($("subtotal").value * .08875).toFixed(2));
$("sales_tax").value = tax;
var total = parseFloat(price + tax).toFixed(2);
$("total").value = total;
}
}
var selectDropdown = function(){
var dropdownValue=document.getElementById("flavors_list").value;
// alert("You selected : " + dropdownValue);
if(dropdownValue == "blueberry vegan" || dropdownValue == "cappuccino vegan" ||
dropdownValue == "carrot vegan" || dropdownValue == "carrot vegan" ||
dropdownValue == "chocolate walnut vegan" || dropdownValue == "chocolate peanut
butter vegan" || dropdownValue == "lavender vegan" || dropdownValue == "lemon
cream vegan" || dropdownValue == "strawberry 2 vegan"){
alert("Adding " + dropdownValue + " to cart.");
cart[cart.length] = dropdownValue + ": $3.25";
update_cart();
} else{
alert("Adding " + dropdownValue + " to cart.");
cart[cart.length] = dropdownValue + ": $2.75";
update_cart();
}
}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home-Little Sweetie Cupcakes</title>
<link href="little_sweetie_styles.css" rel="stylesheet" type="text/css" />
<link rel="Shortcut Icon" href="favicon.ico" />
<script type="text/javascript" src="invoice.js"></script>
</head>
<body onLoad="addOption_list()";>
<div class="cart_content">
<span class="content_title">
Price Calculator
</span>
<p class="bodytext">To place an order, please enter the desired flavor from
the dropdown list:</p>
<FORM name="drop_list" action="yourpage.php" method="POST" >
<SELECT NAME="flavors_list" id="flavors_list"
onchange="selectDropdown()">
<Option value="" >Flavors List</option>
</SELECT>
</form>
<div>
<!--<textarea id="shopping_cart" rows="5" cols="50"></textarea>-->
<table id="invoice">
<tr>
<td width="150"><textarea id="flavor_name" rows="10" cols="40"
disabled="disabled" /></textarea></td>
<td> </td>
<td id="calculator">
<label class="bodytext">Subtotal: </label><input
type="text" id="subtotal" size="10" disabled="disabled"
/><br />
<label class="bodytext">Sales Tax: </label><input
type="text" id="sales_tax" size="10"
disabled="disabled" /><br />
<label class="bodytext">Total: </label><input type="text"
id="total" size="10" disabled="disabled" /><br />
</td>
</tr>
</table>
</body>
</html>
提前致谢
答案 0 :(得分:2)
我在您的代码中看到了多个问题,但如果没有一个工作示例来查看我们可以看到实际HTML和值的位置,则很难确定所有问题是什么。以下是一些问题:
parseInt()
应始终传递第二个参数(基数),否则它会根据内容猜出基数是什么。for (x in a)
来迭代数组的内容。除了数组元素之外,还可以包括添加到数组的属性。使用for (var i = 0; i < array.length; i++)
更安全。parseInt()
和parseFloat()
都不会容忍字符串中的$
,因此您必须先删除它们。在这段代码中,你不清楚你想要迭代什么。通过for
循环的每次传递都使用相同的list
值。它不是迭代一个数组。
for(var i = 0; i < cart.length; i++){
var price = parseFloat(list.substring(list.length - 5));
sum += parseFloat( price.toFixed(2) );
}
仅供参考,从字符串末尾提取数字是非常安全的:
function getNumber(str) {
var matches = str.match(/([\d\.]+)\s*$/)
if (matches) {
return (+matches[1]);
}
return(0);
}
var str = "xxx $99.45\n";
var num = getNumber(str);
答案 1 :(得分:1)
for(var i in cart)
你应该traverse the array使用for循环和计数变量,如下所示。其他好处:无需parseInt
property names。
我提取最后5个字符(这是价格)并将它们相加以得到小计:
for(var i = 0; i < cart.length; i++){
var price = parseFloat(list.substring(list.length - 5));
sum += parseFloat( price.toFixed(2) );
}
是的,对于cart
中的每个项目,您都可以从(相同的)list
字符串的最后五个字符中获得价格。 WTF?
您想要的是获得购物车中每件商品的价格。而且我非常确定不只有&lt; $ 10项目的字符串表示只有4个字符。因此,删除购物车项目的第一个字符(美元符号)并在其上应用parseFloat
:
for (var i=0; i<cart.length; i++) {
var price = parseFloat(cart[i].substring(1));
sum += price;
}
此外,您不应使用parseFloat( price.toFixed(2) );
。除了一些IE错误之外,浮点数学将永远不可靠,并且在不断舍入时不会变得更好。而是使用整数分数计算(尽管JS在技术上没有整数):
var price = Math.floor(parseFloat(str, 10) * 100);