'click'事件侦听器在小屏幕上不起作用

时间:2020-10-04 06:43:39

标签: javascript html html-table click addeventlistener

我有一个表,其每一行都有一个addEventlistener供单击。在较大的屏幕上可以很好地选择行,但是在较小的屏幕上不能选择某些项目。 我为此使用普通的JavaScript。我已经定义了相应的媒体查询,因此我认为这应该不是问题。

这是我的代码:

var table_row = document.querySelectorAll('.table-row'); //all table rows
window.onload = () => { //clear the localstorage from previous sessions
  localStorage.clear();
  table_row.forEach(element => {
    element.addEventListener('click', () => {
      //on click of a row
      id = element.getAttribute('data-id');
      state = element.getAttribute('data-state');
      if (state == 'off') {
        //unselected
        element.style.background = "#742173";
        element.style.color = "white";
        element.setAttribute('data-state', 'on');

        //changed the appearance of current element
        if (prev_element != null) {
          //revert changes to last selection
          console.log('prev_element:' + prev_element.childNodes[1].innerText);
          prev_element.style.background = "#f0efed";
          prev_element.style.color = "black";
          prev_element.setAttribute('data-state', 'off');
        }

        //setting current element ad prev_element
        prev_element = document.getElementById(id);
        console.log('prev_element:' + prev_element.childNodes[1].innerText);
      }
    });
  });
}
<table align="center
        " id='space-table'>
  <thead>
    <tr>
      <td>Spacecraft name</td>
      <td> Origin</td>
      <td> Destination</td>
      <td>Price per person</td>
    </tr>
  </thead>
  <tbody>

    <tr class="table-row" id='row1' data-id="row1" data-state="off">
      <td>ax12</td>
      <td>Sector 3</td>
      <td>Sector 5A-12</td>
      <td>450</td>
    </tr>
    <tr class="table-row" id='row2' data-id="row2" data-state="off">
      <td>ax13</td>
      <td>Crater34</td>
      <td>Sector 3</td>
      <td>145</td>
    </tr>
    <tr class="table-row" id='row3' data-id="row3" data-state="off">
      <td>ax14</td>
      <td>Crater 34</td>
      <td>Sector 3A-5</td>
      <td>250</td>
    </tr>
    <tr class="table-row" id='row4' data-id="row4" data-state="off">
      <td>ax15</td>
      <td>Sector 5A-12</td>
      <td>LM-36 </td>
      <td>125</td>
    </tr>
    <tr class="table-row" id='row5' data-id="row5" data-state="off">
      <td>ax16</td>
      <td>Sector 5A-12</td>
      <td>Crater 34</td>
      <td>210</td>
    </tr>
    <tr class="table-row" id='row6' data-id="row6" data-state="off">
      <td>ax17</td>
      <td>Crater 34</td>
      <td>LM-36</td>
      <td>500</td>
    </tr>
  </tbody>
</table>

0 个答案:

没有答案