JavaScript:if else语句多个条件

3

刚接触JavaScript并尝试创建学费计算器。我需要知道居住地、是否上校园课程以及学分数,然后计算学费。但我无法让if else语句工作。代码只显示了校园课程,但一旦这个问题解决了,我就会添加在线课程等等。感谢任何帮助!

如果在每个班级类型之前询问居住地问题,我可以让此计算器正常运行,但我想只询问一次居住地问题,然后将学费分配到onctut2变量中。我还希望学生能够输入onchours1的小数,但我只能使用整数。我已经尝试过各种if else语句。

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Tuition Calculator</title>
    <script type="text/javascript">// <![CDATA[
    function formHandler(form) {
     var residency = eval(form.residency.value);
        var onctut1 = eval(form.onctut1.value);
        var onchours1 = eval(form.onchours1.value);
     var onctut2 = 0;
        var t1 = onctut2 * onchours1;
        var totalhours = onchours1;
        var oncfee1 = 0;
        var techfee1 = 0;
        var strecfee = 0;
            //Calculate on campus tut
            if (residency == "yes") && (onctut1 == "yes") {
              onctut2 = 252.00;
            } else if (residency == "no") && (onctut1 == "yes") {
              onctut2 = 554.00;
            } else {
              onctut2 = 0;
            }
            //Calculate on campus fees
            if (onchours1 == "1") {
              oncfee1 = 75.25;
            } else if (onchours1 == "2") {
              oncfee1 = 87.5;
            } else if (onchours1 == "3") {
              oncfee1 = 99.75;
            } else if (onchours1 == "4") {
              oncfee1 = 169.5;
            } else if (onchours1 == "5") {
              oncfee1 = 181.75;
            } else if (onchours1 == "6") {
              oncfee1 = 194.0;
            } else if (onchours1 == "7") {
              oncfee1 = 433.25;
            } else if (onchours1 == "8") {
              oncfee1 = 445.5;
            } else if (onchours1 == "9") {
              oncfee1 = 457.75;
            } else if (onchours1 == "10") {
              oncfee1 = 470.0;
            } else if (onchours1 == "11") {
              oncfee1 = 482.25;
            } else if (onchours1 == "12") {
              oncfee1 = 494.5;
            } else if (onchours1 == "13") {
              oncfee1 = 506.75;
            } else if (onchours1 == "14") {
              oncfee1 = 519.0;
            } else if (onchours1 == "15") {
              oncfee1 = 531.25;
            } else if (onchours1 == "16") {
              oncfee1 = 543.5;
            } else {
              oncfee1 = 0;
            }
     //Calculate on tech fee
            if (totalhours == "1") {
              techfee1 = 11.;
            } else if (totalhours == "2") {
              techfee1 = 22.;
            } else if (totalhours == "3") {
              techfee1 = 33.;
            } else if (totalhours == "4") {
              techfee1 = 44.;
            } else if (totalhours == "5") {
              techfee1 = 55.;
            } else if (totalhours == "6") {
              techfee1 = 66.;
            } else if (totalhours == "7") {
              techfee1 = 77.;
            } else if (totalhours == "8") {
              techfee1 = 88.;
            } else if (totalhours == "9") {
              techfee1 = 99.;
            } else if (totalhours == "10") {
              techfee1 = 110.;
            } else if (totalhours == "11") {
              techfee1 = 121.;
            } else if (totalhours == "12") {
              techfee1 = 132.;
            } else if (totalhours == "13") {
              techfee1 = 143.;
            } else if (totalhours == "14") {
              techfee1 = 154.;
            } else if (totalhours == "15") {
              techfee1 = 165.;
            } else if (totalhours == "16") {
              techfee1 = 165.;
            } else {
              techfee1 = 0;
            }
            //Calculate on student rec fee
            if (totalhours > "0") {
              strecfee = 4;
            }
        var fees1 = oncfee1;
     var fees = fees1 + techfee1 + strecfee;
        var cost = t1 + fees;
        form.t1.value = "$" + t1.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        form.fees.value = "$" + fees.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        form.costresult.value = "$" + cost.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
     form.totalhours.value = "" + totalhours;
    }
    // ]]></script>
    </head>
    <body>
    <form method="post" name="testform">
      <div>
        <table
              id="AutoNumber1"
              summary="calculate the cost per semester for 
        graduate students"
            >
          <tbody>
            <tr>
              <td colspan="2"><label for="residency">Are you a Resident? </label>
                <select id="residency" name="residency">
                  <option selected="selected" value="0"> </option>
                  <option value="yes">Yes</option>
                  <option value="no">No</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><label for="onctut1">Will you take an On campus class? </label>
                <select id="onctut1" name="onctut1">
                  <option selected="selected" value="0"> </option>
                  <option value="yes">Yes</option>
                  <option value="no">No</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><label for="onchours1">Select On campus class Credit Hours </label>
                <select id="onchours1" name="onchours1">
                  <option selected="selected" value="0">0</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                  <option value="11">11</option>
                  <option value="12">12</option>
                  <option value="13">13</option>
                  <option value="14">14</option>
                  <option value="15">15</option>
                  <option value="16">16</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><br></td>
            </tr>
            <tr>
              <td colspan="2"><button
                        name="CostResult"
                        onclick="javascript:formHandler(this.form)"
                        type="button"
                      > Calculate Cost </button></td>
            </tr>
            <tr>
              <td colspan="2"><br></td>
            </tr>
            <tr>
              <td><label for="t1">Tuition On Campus Class(es) </label></td>
              <td><input id="t1" name="t1" size="10" type="text" /></td>
            </tr>
            <tr>
              <td><label for="fees">Fees </label></td>
              <td><input id="fees" name="fees" size="10" type="text" /></td>
            </tr>
            <tr>
              <td><label for="costresult">Total Estimated Tuition/Fees Semester Cost </label></td>
              <td><input
                      id="costresult"
                      name="costresult"
                      size="10"
                      type="text"
                    /></td>
            </tr>
            <tr>
              <td><label for="totalhours">Total Credit Hours </label></td>
              <td><input id="totalhours" name="totalhours" size="10" type="text" /></td>
            </tr>
          </tbody>
        </table>
      </div>
    </form>
    </body>
    </html>

当我点击“计算成本”时,表格仍然保持空白。

1
你应该使用 switch 语句 - Scott Marcus
我看了一下 switch 语句,但不确定如何将其应用于我的问题。 - Effy
1
感谢@Rondo的建议,我已经移除了eval。Scott Marcus,我会再次尝试您的建议。我不是程序员,所以非常感谢您的帮助! - Effy
@ScottMarcus,既然你提到了它...我也使用JS很长时间:自从它在浏览器中被引入以及自从90年代中期Netscape的服务器端JavaScript产品。在这个问题的范围内,即浏览器上下文中,我同意eval不是必需的。但是,在受控环境中,例如代码存储,存在一些用例,其中eval()的使用是关键和必要的组件,并且它既有价值又安全。 - Rondo
@Rondo 我甚至不会使用 eval() 来进行代码存储。我会使用 JSON 作为存储格式,然后在提取代码时使用 JSON.parse()。正如我所说,我从未遇到过需要使用 eval() 的用例。99% 的情况下,包含 eval() 的提议解决方案只是解决问题的错误方法,重新设计解决方案将消除对它的需求。 - Scott Marcus
显示剩余5条评论
4个回答

3
if (residency == "yes") && (onctut1 == "yes") {
    onctut2 = 252.00;
} else if (residency == "no") && (onctut1 == "yes") {
    onctut2 = 554.00;
} else {
    onctut2 = 0;
}

我猜问题在于你需要将整个条件用括号括起来,而不是每个条件都加上括号。
if (residency == "yes" && onctut1 == "yes") {
    onctut2 = 252.00;
} else if (residency == "no" && onctut1 == "yes") {
    onctut2 = 554.00;
} else {
    onctut2 = 0;
}

看起来你可以简化代码,而不是使用那些庞大的 if 语句集来处理 techfee1 变量,你可以这样做:

totalhours = +totalhours; // convert it to a number
techfee1 = totalhours * 11;
if (totalhours === 16) {
    techfee1 = 165;
}
if (totalhours > 16 || totalhours < 1) {
    techfee1 = 0;
}

感谢您关于techfee1的提示,非常有效。但我仍然无法让我的变量t1正常工作。 - Effy

2

控制台中出现了三种类型的错误:
1) if语句中的条件必须用括号括起来(完整地),例如:
if (residency == "yes" && onctut1 == "yes")
或者
if ( (residency == "yes") && (onctut1 == "yes") )

2) eval函数(尽可能避免使用)需要接收有效的JavaScript代码。移除eval调用可以解决此问题。

3) >运算符需要数字,而不是字符串。将比较包装在parseInt函数中即可解决此问题。

这是一个已实施这些更改的工作版本:

*--编辑--
我的原始回答只做了上述更改。
此修订版本重构和简化了代码,并提供了更清晰的变量命名。
(我没有完全测试它,所以我不确定我是否正确计算了所有数学问题,但更新它应该要做的最多的事情就是更改一些数字。)
*-- --

function formHandler(form) {
  
  // Gets form inputs
  var residencyInput = form.residency.value,
      oncTutInput = form.onctut1.value,
      oncHoursInput = form.onchours1.value;
  
  // Converts each input (from String) to Boolean or Number (assumes valid input values)
  var residencyBoolean = (residencyInput == "Yes"),
      oncTutBoolean = (oncHoursInput == "Yes"),
      oncHoursNumber = parseInt(oncHoursInput);

  // Sets Hourly onc tut based on residency
  if(residencyBoolean){ oncTutHourly = 252.00; }
  else{ oncTutHourly = 554.00; }

  // Calculates onc fees (defaults to zero, won't change unless onHoursNumber is positive)
  let oncFee = 0;
  if(oncHoursNumber > 0 && oncHoursNumber < 4){
    oncFee = oncHoursNumber * 12.25 + 63;
  }
  else if(oncHoursNumber > 3 && oncHoursNumber < 7){
    oncfee = oncHoursNumber * 12.25 + 120.5;
  }
  else if(oncHoursNumber > 6 && oncHoursNumber < 17){
    oncfee = oncHoursNumber * 12.25 + 347.5;
  }

  // Calculates tech fee (defaults to zero, won't change unless onHoursNumber is positive)
  let techFee = 0;
  // If `oncHoursNumber` is above 15, techfee1 will be 165
  if(oncHoursNumber > 0){
    techfee = Math.min(oncHoursNumber * 11, 165);
  }

  //Calculates student rec fee
  let strecFee = 0;
  if(oncHoursNumber > "0"){ strecFee = 4; }
  
  // Calculates final values
  let oncTutTotal = oncHoursNumber * oncTutHourly; 
  let feesTotal = oncFee + techFee + strecFee;
  let costTotal =  oncTutTotal + feesTotal;

  form.t1.value = "$" + oncTutTotal.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  form.fees.value = "$" + feesTotal.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  form.costresult.value = "$" + costTotal.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  form.totalhours.value = "" + oncHoursNumber;
}
<form method="post" name="testform">
  <div>
    <table
          id="AutoNumber1"
          summary="calculate the cost per semester for 
    graduate students"
        >
      <tbody>
        <tr>
          <td colspan="2"><label for="residency">Are you a Resident? </label>
            <select id="residency" name="residency">
              <option selected="selected" value="0"> </option>
              <option value="yes">Yes</option>
              <option value="no">No</option>
            </select></td>
        </tr>
        <tr>
          <td colspan="2"><label for="onctut1">Will you take an On campus class? </label>
            <select id="onctut1" name="onctut1">
              <option selected="selected" value="0"> </option>
              <option value="yes">Yes</option>
              <option value="no">No</option>
            </select></td>
        </tr>
        <tr>
          <td colspan="2"><label for="onchours1">Select On campus class Credit Hours </label>
            <select id="onchours1" name="onchours1">
              <option selected="selected" value="0">0</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
              <option value="11">11</option>
              <option value="12">12</option>
              <option value="13">13</option>
              <option value="14">14</option>
              <option value="15">15</option>
              <option value="16">16</option>
            </select></td>
        </tr>
        <tr>
          <td colspan="2"><br></td>
        </tr>
        <tr>
          <td colspan="2"><button
                    name="CostResult"
                    onclick="javascript:formHandler(this.form)"
                    type="button"
                  > Calculate Cost </button></td>
        </tr>
        <tr>
          <td colspan="2"><br></td>
        </tr>
        <tr>
          <td><label for="t1">Tuition On Campus Class(es) </label></td>
          <td><input id="t1" name="t1" size="10" type="text" /></td>
        </tr>
        <tr>
          <td><label for="fees">Fees </label></td>
          <td><input id="fees" name="fees" size="10" type="text" /></td>
        </tr>
        <tr>
          <td><label for="costresult">Total Estimated Tuition/Fees Semester Cost </label></td>
          <td><input
                  id="costresult"
                  name="costresult"
                  size="10"
                  type="text"
                /></td>
        </tr>
        <tr>
          <td><label for="totalhours">Total Credit Hours </label></td>
          <td><input id="totalhours" name="totalhours" size="10" type="text" /></td>
        </tr>
      </tbody>
    </table>
  </div>
</form>


谢谢你的帮助。除了我的变量t1显示学费之外,一切都正常工作。我正在尝试看如何使用上面提到的switch语句并将其应用于我的问题。非常感谢! - Effy

2
我想我已经解决了你的T1问题,而且我认为它正在按照你的要求工作!"最初的回答"

 <!doctype html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Tuition Calculator</title>
    <script type="text/javascript">// <![CDATA[
    function formHandler(form) {
     var residency = eval(form.residency.value);
        var onctut1 = eval(form.onctut1.value);
        var onchours1 = eval(form.onchours1.value);
       var onctut2 = 0;
        var totalhours = onchours1;
        var oncfee1 = 0;
        var techfee1 = 0;
        var strecfee = 0;
            //Calculate on campus tut
            if (residency == 0 && onctut1 == 0) {
              onctut2 = 252.00;
            } else if (residency == 1 && onctut1 == 0) {
              onctut2 = 554.00;
            } else {
              onctut2 = 0;
            }
            //Calculate on campus fees
            if (onchours1 == "1") {
              oncfee1 = 75.25;
            } else if (onchours1 == "2") {
              oncfee1 = 87.5;
            } else if (onchours1 == "3") {
              oncfee1 = 99.75;
            } else if (onchours1 == "4") {
              oncfee1 = 169.5;
            } else if (onchours1 == "5") {
              oncfee1 = 181.75;
            } else if (onchours1 == "6") {
              oncfee1 = 194.0;
            } else if (onchours1 == "7") {
              oncfee1 = 433.25;
            } else if (onchours1 == "8") {
              oncfee1 = 445.5;
            } else if (onchours1 == "9") {
              oncfee1 = 457.75;
            } else if (onchours1 == "10") {
              oncfee1 = 470.0;
            } else if (onchours1 == "11") {
              oncfee1 = 482.25;
            } else if (onchours1 == "12") {
              oncfee1 = 494.5;
            } else if (onchours1 == "13") {
              oncfee1 = 506.75;
            } else if (onchours1 == "14") {
              oncfee1 = 519.0;
            } else if (onchours1 == "15") {
              oncfee1 = 531.25;
            } else if (onchours1 == "16") {
              oncfee1 = 543.5;
            } else {
              oncfee1 = 0;
            }
     //Calculate on tech fee
            if (totalhours == "1") {
              techfee1 = 11.;
            } else if (totalhours == "2") {
              techfee1 = 22.;
            } else if (totalhours == "3") {
              techfee1 = 33.;
            } else if (totalhours == "4") {
              techfee1 = 44.;
            } else if (totalhours == "5") {
              techfee1 = 55.;
            } else if (totalhours == "6") {
              techfee1 = 66.;
            } else if (totalhours == "7") {
              techfee1 = 77.;
            } else if (totalhours == "8") {
              techfee1 = 88.;
            } else if (totalhours == "9") {
              techfee1 = 99.;
            } else if (totalhours == "10") {
              techfee1 = 110.;
            } else if (totalhours == "11") {
              techfee1 = 121.;
            } else if (totalhours == "12") {
              techfee1 = 132.;
            } else if (totalhours == "13") {
              techfee1 = 143.;
            } else if (totalhours == "14") {
              techfee1 = 154.;
            } else if (totalhours == "15") {
              techfee1 = 165.;
            } else if (totalhours == "16") {
              techfee1 = 165.;
            } else {
              techfee1 = 0;
            }
            //Calculate on student rec fee
            if (totalhours > "0") {
              strecfee = 4;
            }
        var fees1 = oncfee1;
       var fees = fees1 + techfee1 + strecfee;
        var t1 = onctut2 * onchours1;
        var cost = t1 + fees;
        form.t1.value = "$" + t1.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        form.fees.value = "$" + fees.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        form.costresult.value = "$" + cost.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
     form.totalhours.value = "" + totalhours;
    }
    // ]]></script>
    </head>
    <body>
    <form method="post" name="testform">
      <div>
        <table
              id="AutoNumber1"
              summary="calculate the cost per semester for 
        graduate students"
            >
          <tbody>
            <tr>
              <td colspan="2"><label for="residency">Are you a Resident? </label>
                <select id="residency" name="residency">
                  <option selected="selected" value="0"> </option>
                  <option value="0">Yes</option>
                  <option value="1">No</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><label for="onctut1">Will you take an On campus class? </label>
                <select id="onctut1" name="onctut1">
                  <option selected="selected" value="0"> </option>
                  <option value="0">Yes</option>
                  <option value="1">No</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><label for="onchours1">Select On campus class Credit Hours </label>
                <select id="onchours1" name="onchours1">
                  <option selected="selected" value="0">0</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                  <option value="11">11</option>
                  <option value="12">12</option>
                  <option value="13">13</option>
                  <option value="14">14</option>
                  <option value="15">15</option>
                  <option value="16">16</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><br></td>
            </tr>
            <tr>
              <td colspan="2"><button
                        name="CostResult"
                        onclick="javascript:formHandler(this.form)"
                        type="button"
                      > Calculate Cost </button></td>
            </tr>
            <tr>
              <td colspan="2"><br></td>
            </tr>
            <tr>
              <td><label for="t1">Tuition On Campus Class(es) </label></td>
              <td><input id="t1" name="t1" size="10" type="text" /></td>
            </tr>
            <tr>
              <td><label for="fees">Fees </label></td>
              <td><input id="fees" name="fees" size="10" type="text" /></td>
            </tr>
            <tr>
              <td><label for="costresult">Total Estimated Tuition/Fees Semester Cost </label></td>
              <td><input
                      id="costresult"
                      name="costresult"
                      size="10"
                      type="text"
                    /></td>
            </tr>
            <tr>
              <td><label for="totalhours">Total Credit Hours </label></td>
              <td><input id="totalhours" name="totalhours" size="10" type="text" /></td>
            </tr>
          </tbody>
        </table>
      </div>
    </form>
    </body>
    </html>


谢谢Tori!昨天我无法让它工作,可能是var t1的格式问题。我非常感谢你的跟进! - Effy
没问题!你能用绿色勾号标记一下这个解决方案是否对你有帮助吗? :) - Tori

0
我会诚实地使用 switch 语句。它比在 if/else 中有多个条件更有意义。https://www.w3schools.com/js/js_switch.asp
//Calculate on campus tut
        if (residency == 0 && onctut1 == 0) {
          onctut2 = 252.00;
        } else if (residency == 1 && onctut1 == 0) {
          onctut2 = 554.00;
        } else {
          onctut2 = 0;
        }

我看了一下 switch 语句,但不确定如何将其应用于我的问题。 - Effy
1
要按照您目前的方式进行操作,首先您需要不将“是”和“否”作为表单中的值传递。如果这样做,您可以更改我在答案中添加的代码块,然后它就会开始计算。可能需要进行一些微调,但那应该是一个好的开端。 - Tori
现在除了 var t1 = onctut2 * onchours1; 之外,其他都正常工作了。离成功更进一步了,谢谢! - Effy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接