2016-06-07 43 views
0

我在嘗試使用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

這將有助於如果你的小提琴didnt錯誤 - '遺漏的類型錯誤:TDS [TD]閱讀進度是不是function'。另外,你的問題不是特別清楚你想要做什麼。 – Jamiec

+0

現在的問題是:如何將它轉換爲使用數組而不是當前設置?通過保持這種方式,它包含了比需要更多的代碼。通過使用一個數組,我知道可以使它更短,並且當我想要實現更多信息時,只需要一行信息來打印新的表格......隨意再次提問,否則就會承認它可能看起來有點不清楚 – ImNewToThis

回答

0

環繞你的事件監聽器在if語句可以確保目前的元素的廁所p是一個對象。

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

JSFiddle