您好,我是新手,我正在尝试使这个运费计算器代码工作。这是我到目前为止所做的。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
ent"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Calculate Shipping</title>
<script type="text/javascript">
/* <![CDATA[ */
var price = 0;
var shipping = (calculateShipping(price););
var total = price + shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else {
return price * 10 / 100;
break;
}
}
window.alert("Your total is $" + total + ".");
/* ]]> */
</script>
</head>
<body>
<form name="shipping" action="">
<p>Purchase Price: $
<input type="text" name="price" />
<input type="button" value="Calculate Shipping" onclick="calculateshipping(price);" />
</p>
</form>
</body>
</html>
答案 0 :(得分:1)
将您的onclick代码更改为:
calculateShipping(document.getElementById('price').value);
编辑,尝试此代码,它应该可以工作:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ent"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Calculate Shipping</title>
<script type="text/javascript">
/* <![CDATA[ */
var price = 0;
var shipping = calculateShipping(price);
function calculateShipping(price){
var result = 0;
if (price <= 25){
result = 1.5;
}
else{
result = price * 10 / 100;
}
var total = result + (price - 0);
window.alert("Shipping is $" + result + ". Total is $" + total +".");
}
/* ]]> */
</script>
</head>
<body>
<p>Purchase Price: $
<input type="text" name="price" id="price" />
<input type="button" value="Calculate Shipping" onclick="calculateShipping(document.getElementById('price').value);" /></p>
</body>
</html>
答案 1 :(得分:1)
我认为最好的方法(不使用任何库,如JQuery)如下:
<!DOCTYPE html>
<html>
<head>
<title>Calculate Shipping</title>
<script type="text/javascript">
window.addEventListener('load', function(){
var priceField = document.getElementById('price');
var calculateButton = document.getElementById('calculate');
var totalField = document.getElementById('total');
calculateButton.addEventListener('click', function(){
var price = parseInt(priceField.value);
var shipping = calculateShipping(price);
var total = price + shipping;
totalField.value = "Your total is $" + total + ".";
});
function calculateShipping(price){
return (price <= 25) ? 1.5 : price / 10;
}
});
</script>
</head>
<body>
<h1>Purchase Price:</h1>
<label>Price:</label><input type="text" id="price" />
<button id="calculate">Calculate Shipping</button>
<label>Total:</label>
<input type="text" id="total" disabled="disabled" />
</body>
</html>
这里我介绍一些好的做法,比如: