我需要帮助为document.querySelectorAll创建一个for循环

时间:2016-02-10 04:01:50

标签: javascript forms loops

我需要帮助为document.querySelectorAll创建一个for循环(" .suit")。我正在尝试创建一个输入生日的表单,输出总共有365个选项。示例输出put在HTML中。

    <html>
    <head> 
  <style type="text/css">
 .suit {
    display: none;
 }

 .suit.visible {
display: block;
 }
 </style>
 <script type="text/javascript">


   window.onload = function() {
    var monthSelection = document.querySelector("#month");
    var daySelection = document.querySelector("#day");
    var submitButton = document.querySelector("#submit");
    submitButton.onclick = function() {
    document.querySelectorAll(".suit").setAttribute("class", "suit     visible");
       // TODO hide everything else
    }

  }

  </script>

 </head>
  <body>
   Date Of Birth: <br>
<select id="month" name="month">
<option value="na">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>

<select id="day" name="day">
<option value="na">Day</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>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>

<button id="submit">Submit</button>

<div class="suit" month="8" day="27">Queen of Hearts, 10 of clubs</div>

<!-- TODO content -->

1 个答案:

答案 0 :(得分:0)

querySelectorAll()返回一个名为nodeList的类数组数据结构。您可以使用for循环进行迭代。

submitButton.onclick = function() {
    var items = document.querySelectorAll(".suit");
    for (var i = 0; i < items.length; i++) {
       items[i].className = "suit visible";
    }
}