如何获得if / else语句在函数内部工作

时间:2019-02-01 05:10:48

标签: javascript html webpage

我正在尝试在函数内使用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
}

2 个答案:

答案 0 :(得分:3)

您有几个问题:

  1. 您两次声明p。虽然这不是完全错误的,但是没有必要这样做。删除第一个var p = document....

  2. return s在显示结果之前。使用return将停止该函数的运行,从而使其下的所有代码均无法运行。删除它(如果您不对其进行任何操作)或将其移至函数底部。

  3. 尽管这不是必需的更改,但是您可以声明var svar 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;
}