我正在尝试在函数内使用if / else语句来使之超过50个订单免运费(s = 0)。
我以前的运费等于订单成本的15%,现在已注释掉。在我尝试添加if / else语句之前,该函数确实起作用。
没有显示错误代码。
function estcost() {
var p = document.getElementById("price").value; //gets price for plant as entered in box by user
var p = parseFloat(document.getElementById("price").value);
var t = 0.086 * p; //calculates arizona sales tax
//var s = 0.15*p;//calculates shipping cost based off of 15% of plant cost
var s;
if (p < 50) {
s = 0.15 * p; //shipping for orders under $50
} else {
s = 0; //shipping for orders $50 and over
}
return s;
var c = t + s + Number(p); //calculates final cost
var f = '$' + c.toFixed(2); //rounds cost to 2 decimal places
document.getElementById("result").innerHTML = f; //allows me to call f in html
}
答案 0 :(得分:3)
您有几个问题:
您两次声明p
。虽然这不是完全错误的,但是没有必要这样做。删除第一个var p = document....
您return s
在显示结果之前。使用return
将停止该函数的运行,从而使其下的所有代码均无法运行。删除它(如果您不对其进行任何操作)或将其移至函数底部。
尽管这不是必需的更改,但是您可以声明var s
为var s = 0
,并且仅在p < 50
时才进行更改,从而可以删除{{1 }}。
请参见下面的工作示例:
else
function estcost() {
var p = parseFloat(document.getElementById("price").value);
var t = 0.086 * p; //calculates arizona sales tax
var s = 0;
if (p < 50) {
s = 0.15 * p; //shipping for orders under $50
}
var c = t + s + Number(p); //calculates final cost
var f = '$' + c.toFixed(2); //rounds cost to 2 decimal places
document.getElementById("result").innerHTML = f; //allows me to call f in html
return s; // move to bottom
}
答案 1 :(得分:1)
问题是您的return
语句在您的函数中为时过早-它使其余函数无法执行。将return
语句放在函数底部应该可以解决此问题:
function estcost() {
var p = document.getElementById("price").value; //gets price for plant as entered in box by user
var p = parseFloat(document.getElementById("price").value);
var t = 0.086 * p; //calculates arizona sales tax
//var s = 0.15*p;//calculates shipping cost based off of 15% of plant cost
var s;
if (p < 50) {
s = 0.15 * p; //shipping for orders under $50
} else {
s = 0; //shipping for orders $50 and over
}
var c = t + s + Number(p); //calculates final cost
var f = '$' + c.toFixed(2); //rounds cost to 2 decimal places
document.getElementById("result").innerHTML = f; //allows me to call f in html
return s;
}