将计算器转换为2D数组

时间:2016-06-07 15:49:52

标签: javascript html

我正在尝试使用Javascript将当前的计算器转换为two-dimentional array。此外,我希望计算器能够使用<input type"date"

计算在两个不同日历中选择的天数

当前代码:     

  <head>
  <meta charset="UTF-8">
    <title>Demo</title>
    <style type="text/css">
      table,
      td,
      th {
        border: 1px solid black;
      }

      table {
        border-collapse: collapse;
      }

      .selected {
        background-color: lightblue;
      }

    </style>
  </head>

  <body>
    <table>
      <tr>
        <th bgcolor="b8cce4">Destinasjon</td>
          <th>Rental Gear</td>
            <th>Pre-heated hut</td>
              <th>Extra firewood</td>
                <th>Ski-pass</td>
                  <th>Internet connection</td>
                    <th>Final price</td>
      </tr>
      <tr>
        <td bgcolor="b8cce4"><b>Trysil</b></td>
        <td>100</td>
        <td>50</td>
        <td>20</td>
        <td>150</td>
        <td>25</td>
        <td>$</td>
      </tr>
      <tr>
        <td bgcolor="b8cce4"><b>Kongsberg</b></td>
        <td>75</td>
        <td>50</td>
        <td>30</td>
        <td>125</td>
        <td>20</td>
        <td>$</td>
      </tr>
      <tr>
        <td bgcolor="b8cce4"><b>Beitostølen</b></td>
        <td>120</td>
        <td>30</td>
        <td>40</td>
        <td>100</td>
        <td>75</td>
        <td>$</td>
      </tr>

<!--here I want it to ask for date using <input type="date" name="example">
 Example: from <input type="date" name="from"> to <input type="date" name="to">
 then calculate price for the amount of days that becomes, lets say each day is 1000.
 this is to be calculated together with what is selected in table-->

      <script type="text/javascript">
        (function() {
          var tds = document.querySelectorAll('tr td:not(:last-child)');
          for (var td in tds) {
            tds[td].addEventListener('click', function(evt) {
              evt.target.classList.toggle('selected');
              var total = 0;
              var parentTr = evt.target.parentNode;
              var selected = parentTr.querySelectorAll('.selected');
              for (var k in selected) {
                if (selected[k].innerText) {
                  total += parseInt(selected[k].innerText);
                }
              }
              parentTr.querySelector('td:last-child').innerText = total;
            });
          }
        })();
        <!-- The script currently works with this setup, but I want to change it, I want it to be a two dimentional array setup. I mean, so it prints the current table with pre-printed info in the script  -->
      </script>
  </body>

</html>

如果有任何不清楚的地方,请随时提出,并尽可能地解释

JSFIDDLE:https://jsfiddle.net/zfcknc5m/1/

1 个答案:

答案 0 :(得分:0)

将事件侦听器置于if语句中,以确保for循环中的当前元素是对象。

if(typeof tds[td]==="object")

JSFiddle