简体   繁体   English

if语句中的for循环

[英]If statement within a for loop

So this is an assignment I was just given in my web class, and to be honest I haven't had a single instructor clearly explain how a for loop works. 所以这是我刚刚在我的网络课程中给出的一项任务,说实话,我没有一位教师清楚地解释for循环是如何工作的。 Basically instead of having a bunch of different var defined and a bunch of if statements for each one, I need one var for all the inputs, and a for loop that will run through each input, and add to the total. 基本上不是为每个输入定义一堆不同的var和一堆if语句,我需要一个var用于所有输入,一个for循环将运行每个输入,并添加到总数。 I included my code that worked that doesn't have a loop, and my attempt at using a loop to do it . 我包含了我的代码,它没有循环,我尝试使用循环来完成它。 I just really can't grasp loops, and reading around online hasn't helped at all. 我真的无法掌握循环,在网上阅读根本没有帮助。

This code does what the end goal is: 此代码执行最终目标:

<article>
      <h2>Food Menu</h2>
      <form>
         <input type="checkbox" id="item1" value="8" />
         <label for="item1">Fried chicken ($8.00)</label>
         <input type="checkbox" id="item2" value="9" />
         <label for="item2">Honey Baked Ham ($9.00)</label>
         <input type="checkbox" id="item3" value="8" />
         <label for="item3">Mac and Cheese ($8.00)</label>
         <input type="checkbox" id="item4" value="13" />
         <label for="item4">Grilled Salmon ($13.00)</label>
         <input type="checkbox" id="item5" value="6" />
         <label for="item5">Side salad ($6.00)</label>
         <input type="submit" id="submit" value="Submit" />
      </form>

       <script>

       function calcTotal(){
           var itemTotal=0;
           var item1=document.getElementById("item1");
           var item2=document.getElementById("item2");
           var item3=document.getElementById("item3");
           var item4=document.getElementById("item4");
           var item5=document.getElementById("item5");
           if(item1.checked==true){itemTotal+=8;}
           if(item2.checked==true){itemTotal+=9;}
           if(item3.checked==true){itemTotal+=8;}
           if(item4.checked==true){itemTotal+=13;}
           if(item5.checked==true){itemTotal+=6;}
           var salesTaxRate=0.07;
           var orderTotal=itemTotal+(itemTotal*salesTaxRate);
           document.getElementById("total").innerHTML="Your order total is $"+orderTotal,false;

       }

        document.getElementById("submit").addEventListener("click",calcTotal,false);

        ;
       </script>
   </article>

This code is my attempt at getting the same result with a for loop. 这段代码是我尝试用for循环获得相同的结果。

<article>
      <h2>Food Menu</h2>
      <form>
         <input type="checkbox" id="item1" value="8" />
         <label for="item1">Fried chicken ($8.00)</label>
         <input type="checkbox" id="item2" value="9" />
         <label for="item2">Honey Baked Ham ($9.00)</label>
         <input type="checkbox" id="item3" value="8" />
         <label for="item3">Mac and Cheese ($8.00)</label>
         <input type="checkbox" id="item4" value="13" />
         <label for="item4">Grilled Salmon ($13.00)</label>
         <input type="checkbox" id="item5" value="6" />
         <label for="item5">Side salad ($6.00)</label>
         <input type="submit" id="submit" value="Submit" />
      </form>

       <script>

       function calcTotal(){
           var itemTotal=0;
           var items = document.getElementById("input");
           var salesTaxRate=0.07;
           var orderTotal=itemTotal+(itemTotal*salesTaxRate);
           document.getElementById("total").innerHTML="Your order total is $"+orderTotal,false;
           for(i=0: i < items.length; i++){
               if(input.items[i].checked==true)
                   orderTotal+=(items[i].value*1);
           }
           window.alert(itemTotal)
       }

        document.getElementById("submit").addEventListener("click",calcTotal,false);

        ;
       </script>
   </article>

So a lot of things you can improve in this code for sure but let me just stick to the for loop knowledge you seek for now. 所以你可以在这段代码中改进很多东西,但是让我坚持你现在寻求的for循环知识。

I'm going to re-arrange your code in the following manner: 我将以下列方式重新安排您的代码:

var itemTotal=0;

var item1=document.getElementById("item1");
if(item1.checked==true){itemTotal+=8;}

var item2=document.getElementById("item2");
if(item2.checked==true){itemTotal+=9;}

var item3=document.getElementById("item3");
if(item3.checked==true){itemTotal+=8;}

var item4=document.getElementById("item4");
if(item4.checked==true){itemTotal+=13;}

var item5=document.getElementById("item5");
if(item5.checked==true){itemTotal+=6;}

As you can see we have now chunked your code into two steps: 正如您所看到的,我们现在将您的代码分为两个步骤:

  1. Get something (checked state) 得到的东西(检查状态)
  2. Add it to total (price is hardcoded). 将其添加到总计(价格是硬编码的)。

Lets upgrade this to make it a bit more dynamic. 让我们升级一下,让它更有活力。

var itemTotal=0;

var i=1;
var item1=document.getElementById("item"+i);
if(item1.checked==true){itemTotal+=parseInt(item1.value);}

i++
var item2=document.getElementById("item"+i);
if(item2.checked==true){itemTotal+=parseInt(item2.value);}

i++
var item3=document.getElementById("item"+i);
if(item3.checked==true){itemTotal+=parseInt(item3.value);}

i++
var item4=document.getElementById("item"+i);
if(item4.checked==true){itemTotal+=parseInt(item4.value);}

i++
var item5=document.getElementById("item"+i);
if(item5.checked==true){itemTotal+=parseInt(item5.value);}

You'll notice the parseInt function required here since doing + on strings will just concatenate. 你会注意到这里需要的parseInt函数,因为在字符串上做+会连接。 If you've understood what we've done this far then we can just take it one step further with a for loop. 如果您已经理解了我们迄今为止所做的工作,那么我们可以通过for循环更进一步。

var itemTotal=0;

for (var i=1; i<6; i++) {
  var item=document.getElementById("item"+i);
  if(item.checked==true){itemTotal+=parseInt(item.value);}
}

Hope this makes sense. 希望这是有道理的。 We've just used some variables ( i in particular) to get the items dynamically and also to update the total amount. 我们刚刚使用了一些变量(尤其是i )来动态获取项目并更新总量。 For loops (and loops in general) are used for repeated work. 对于循环(和一般循环)用于重复工作。 It's just a matter of finding out what needs to be repeated and how many times you need to repeat. 这只是找出需要重复的内容以及需要重复多少次的问题。 You can set the starting and ending values of your loop variable to make things convenient for you. 您可以设置循环变量的起始值和结束值,以方便您使用。

A couple things to note: 有几点需要注意:

  • document.getElementsByTagName("input") will generate a list of the input DOM elements by tag name so that IDs are no longer necessary. document.getElementsByTagName("input")将按标签名称生成输入DOM元素的列表,以便不再需要ID。 You could also put a starting ID on the form tag, and then do form.getElementsByTagName 您还可以在表单标记上放置起始ID,然后执行form.getElementsByTagName
  • you had no result div to display the total results, causing a js error, which stops execution 你没有结果div显示总结果,导致js错误,停止执行
  • you had syntax errors with input.items in the for loop 你在for循环中输入了input.items语法错误

 function myFunction() { var itemTotal = 0; var items = document.getElementsByTagName("input") var salesTaxRate = 0.07; var orderTotal = 0; for (i = 0; i < items.length; i++) { if (items[i].checked == true) { itemTotal += (items[i].value * 1); } } orderTotal = itemTotal + (itemTotal * salesTaxRate); document.getElementById("total").innerHTML = "Your order total is $" + orderTotal; return false; } 
 <article> <h2>Food Menu</h2> <form action="" onsubmit="return myFunction();"> <input type="checkbox" id="item1" value="8" /> <label for="item1">Fried chicken ($8.00)</label> <input type="checkbox" id="item2" value="9" /> <label for="item2">Honey Baked Ham ($9.00)</label> <input type="checkbox" id="item3" value="8" /> <label for="item3">Mac and Cheese ($8.00)</label> <input type="checkbox" id="item4" value="13" /> <label for="item4">Grilled Salmon ($13.00)</label> <input type="checkbox" id="item5" value="6" /> <label for="item5">Side salad ($6.00)</label> <input type="submit" id="submit" value="Submit" /> </form> <div id="total"></div> </article> 

  <h2>Food Menu</h2>
  <form>
     <input type="checkbox" id="item1" value="8" />
     <label for="item1">Fried chicken ($8.00)</label>
     <input type="checkbox" id="item2" value="9" />
     <label for="item2">Honey Baked Ham ($9.00)</label>
     <input type="checkbox" id="item3" value="8" />
     <label for="item3">Mac and Cheese ($8.00)</label>
     <input type="checkbox" id="item4" value="13" />
     <label for="item4">Grilled Salmon ($13.00)</label>
     <input type="checkbox" id="item5" value="6" />
     <label for="item5">Side salad ($6.00)</label>
  <!-- I changed this to be a button just so you can see the results, probably need to be a submit later again, but for now this way you can see how the result changes.   -->         
     <input type="button" id="submit" value="Submit" />
  </form>

  <!-- You need an element with id 'total', you were calling it to set the result for total, but it didn't exist -->
  <label id="total"></label>
   <script>

   function calcTotal(){
       var itemTotal=0;

       //use querySelectorAll to get and array with all the inputs, getElementById will return just one element
       var items = document.querySelectorAll("input");
       var salesTaxRate= 0.07;
       var orderTotal=   0;


       // you have a sintax error here
       for(i=0; i < items.length; i++){
           if(items[i].checked==true) {
               itemTotal= parseInt(items[i].value);
               itemTotal= parseFloat(itemTotal + (itemTotal*salesTaxRate));
               orderTotal+=itemTotal;
            }
       }

       // you need to display orderTotal, that is the variable you are incrementing, no itemTotal
         document.getElementById("total").innerHTML="Your order total is $"+orderTotal;

       window.alert(orderTotal)
   }

    document.getElementById("submit").addEventListener("click",calcTotal,false);


   </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM