更熟练的方式编写if-else语句?

时间:2019-01-16 01:56:14

标签: javascript html if-statement

我目前正在建立一个网站来计算用户费用,并以此来帮助人们省钱。本节的其中一部分采用if-else语句,接受用户输入并根据用户输入显示特定段落。

这是我想到的第一个设计。它确实按照设计的方式工作,但我希望有一种更简洁的方式可以编写此代码。我觉得我隐藏和显示div元素的方式可以清理。这是js.fiddle的链接:https://jsfiddle.net/eb6y9o75/1/

  

Blockquote

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
    #PriceOfCar-Wrapper {
        display:none;
    }
    #WSYD-Car-20 , #WSYD-Car-40 , #WSYD-CantBuyCarForForty , #I- 
    CongratsTextCar , #I-DidntWantCar{
        Display:none;
        margin:5px;
        padding:5px;
    }
    </style>
   </head>
   <body>
   <script>            
   function MathFunctions() {
     var vMoneyAfterExpensesWOSaving = 758;
     var vMoneySavedTwenty = 758 * .20;
     var vMoneySavedForty = 758 * .40;
     var vMoneyAfterExpensesWSaving40 = vMoneyAfterExpensesWOSaving - 
     vMoneySavedForty;
     // Buying a car for $10,000
     var vMonthsForCar = 0;
     var vPriceOfCar = parseInt(parseFloat(0));
     var vMoneyNeededMonthlyForCar = 0;
     var vWSYDCar20 = document.getElementById('WSYD-Car-20').id;
     var vWSYDCar40 = document.getElementById('WSYD-Car-40').id;
     var vCongratsTextCar = document.getElementById('I CongratsTextCar').id;
        vPriceOfCar = document.getElementById('PriceOfCar').value;
        console.log(vMonthsForCar , 'Months For Car should equal 0');

        if(document.getElementById('PriceOfCar-Wrapper').style.display === 'none'){
            document.getElementById('I-DidntWantCar').style.display = 'block';
            document.getElementById('I-CongratsTextCar').style.display = 'none';
            console.log(document.getElementById('I-DidntWantCar').style.display);
            document.getElementById('WSYD-Car-20').style.display = 'none';
            document.getElementById('WSYD-Car-40').style.display = 'none';
            vPriceOfCar = 0;
        }

        else if( vPriceOfCar > 0){

            while(vMoneyNeededMonthlyForCar < vPriceOfCar) {
                console.log(vMoneyNeededMonthlyForCar);
                vMoneyNeededMonthlyForCar = +vMoneyNeededMonthlyForCar + +vMoneySavedTwenty;
                vMonthsForCar++;
            }
        }
        else{

        }
        if( vMonthsForCar == 1 ){
            document.getElementById('I-CongratsTextCar').style.display = 'block';
            document.getElementById('WSYD-Car-20').style.display = 'none';
            document.getElementById('WSYD-Car-40').style.display = 'none';
            document.getElementById('I-DidntWantCar').style.display = 'none';
        }
        else if(vMonthsForCar > 1) {
            vMoneyNeededMonthlyForCar = vPriceOfCar / vMonthsForCar;
            document.getElementById('WSYD-Car-20').style.display = 'block';
            console.log(vPriceOfCar);
            document.getElementById('I-MonthsNeededToBuyCar').innerHTML = vMonthsForCar;
            parseInt(parseFloat(vMoneyNeededMonthlyForCar)).toFixed(2);
            document.getElementById('I-PaymentForCar').innerHTML = vMoneyNeededMonthlyForCar;
            document.getElementById('I-CongratsTextCar').style.display = 'none';
            document.getElementById('WSYD-Car-40').style.display = 'none';
            document.getElementById('I-PriceOfCar').innerHTML = vPriceOfCar;
        }
        else {}
        if (vPriceOfCar == 0){ 
            document.getElementById('I-DidntWantCar').style.display = 'block';
            document.getElementById('WSYD-Car-20').style.display = 'none';
            document.getElementById('WSYD-Car-40').style.display = 'none';
            document.getElementById('I-CongratsTextCar').style.display = 'none';
        }
        else if (vMoneyAfterExpensesWSaving40 > (vMoneySavedTwenty * 2)) {
            document.getElementById('WSYD-Car-40').style.display = 'block';
            console.log(vPriceOfCar);
            document.getElementById('I-PriceOfCarForty').innerHTML = vPriceOfCar;
            document.getElementById('I-MonthsNeededToBuyCarForty').innerHTML = vMoneyNeededMonthlyForCar;
            document.getElementById('I-PaymentForCarForty').innerHTML = vMoneyNeededMonthlyForCar * 2;
            document.getElementById('I-PaymentForCartwenty').innerHTML = vMoneySavedTwenty
        }
        else {
        }
}
</script>
<a href="#"><button style="position:relative;top:30px;" type="button" onclick="MathFunctions()">Submit</button></a>
<section style="position:relative;top:30px;">
<h4>Would you like to purchase a car?</h4> <input type="radio" value="yes" id="CarRadio-yes" onclick="document.getElementById('PriceOfCar-Wrapper').style.display = 'block'" name="group1">Yes
<input type="radio" value="no" onclick="document.getElementById('PriceOfCar-Wrapper').style.display = 'none'" id="CarRadio-No" name="group1">No 
<br>
<div id="PriceOfCar-Wrapper">
    How much are you willing to spend <input type="Text" value="0" id="PriceOfCar">
</div>
<br>
</section>
</tr>
<tr>
<td class="Sub-Title-td" id="Sub-Title-Show-Car" style="display:none">
<h2>How to buy a car on your current expenses</h2>
<p>One way to buy a car is throught the 20/4 rule</p>
<br>
</p>
<section id="I-DisplayPriceOfCar">
<h2>What Should You Do?</h2>
<div id="WSYD-Car-20" style="display:none;">
    Based on saving the recommended amount of 20% from your check, at $<span id="I-PaymentForCar"></span>. It will take you roughly <span id="I-MonthsNeededToBuyCar"></span> months to save up enough for a car worth <span id="I-PriceOfCar"></span>
    <br>
</div>
<div id="WSYD-Car-40" style="display:none;">
     After saving 20% it seems you still have some extra cash left. Instead, if you were to save 40% it would take you <span id="I-MonthsNeededToBuyCarForty"></span> months to save up enough money to buy a car that is worth $<span id="I-PriceOfCarForty"></span>. Saving 40% would increase that amount that you are saving from $<span id="I-PaymentForCartwenty"></span> to $<span id="I-PaymentForCarForty"></span>.
    <br>
</div>
<div id="WSYD-CantBuyCarForForty">Sadly, You cant afford to put away anymore money. here are some ways we recommend making more money
    <ul>
        <li>Pick up extra hours at work</li>
        <li>Earn a passing income</li>
        <li>Start a blog</li>
    </ul>
</div>
<p id="I-CongratsTextCar">The Money you are currently saving per month is greater than the price of the car! Congratulations!</p>

<div id="I-DidntWantCar">You made it clear that you didn't want to buy a car!</div>
</section>
</td>
</tr>
</table>
</body>

一切似乎都正常,但是我将在一页上包含3-5个,所以我想知道是否有一种更干净的方式编写此内容,或者我所做的事情被认为是不好的做法。

预期结果 可能有多种选择, 用户选择他们不想买车-在这种情况下,文本显示告诉用户他们不想买车

用户选择要购买汽车,但未输入汽车的价值。默认价格为0。-再次显示此文本,通知用户他们不想买车。

另一种情况是,用户决定将一辆汽车添加到他们的预算中,但根据他们的收入,他们一个月内的收入要比整辆汽车的成本高-在这种情况下,显示的文字会告知用户他们一个月的收入比购车成本还高。

最后两种情况是用户选择要购买的汽车,并且输入的值大于他们的月收入。这将执行一些计算,并告知用户他们需要节省多少钱,以及他们需要花多长时间才能为他们购买汽车节省足够的钱。

如果用户每月赚取的钱足以使他们节省两倍的钱,则会出现文本,提示用户可以节省多少钱以及购买所需汽车需要多长时间。但是如果用户没有赚到这笔额外的钱。文字会通知用户他们没有足够的额外钱来储蓄,并且会通知他们快速赚钱的方法。

感谢所有帮助:)

1 个答案:

答案 0 :(得分:0)

我首先要获取DOM中的所有元素,即

var myIdIWant = document.getElementById('someid')

那样,不用在上面输入,我可以说类似 myIdIwant.style.display = 'none' 似乎您还有很多悬而未决的问题,可能使用if / else语句代替

if(foo) {
//do something
}
elseif(bar) { 
//do something 
}
else{}

您还可以探索switch语句以清理冗长的逻辑,它们使您可以基于许多类似这样的不同状态执行操作

var x = 5 //Some number
switch(x) {
  case 1:
      //do something
  break
  case 2:
  case 3:
      //do something else if it is 2 or 3 
      break
  default:
      // do something if it is none of those cases
      break
 }