使用addEventlistener对表进行排序

时间:2017-03-25 16:37:29

标签: javascript html inline addeventlistener

我试图在Google Chrome扩展程序中对表格进行排序,但不允许使用任何内联JavaScript。这就是我使用addEventListener的原因,但它根本没有变化。

HTML文件

<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../CSS/entwickler.css">
    <script src="../JS/entwickler.js"></script>
</head>

<body>
    <header>
        <img src="../back.png" class="cover" id="idback"> <!--back-->
        <h1 class="toolbaralign">Entwickleransicht</h1>
        <img src="../send.png" class="cover right" id="idloginToJson"> <!-- : Menu Icon--->
    </header>
    <table id="idsort">
        <thead>
            <tr><th id="one">Status</th><th id="two">Betreff</th><th id="three">Erstelldatum</th></tr>
        </thead>
        <tbody>
            <tr><td>Gelöst</td><td>Betreff 1</td><td>K</td></tr>
            <tr><td>In Bearbeitung</td><td>P</td><td>J</td></tr>
            <tr><td>Offen</td><td>Z</td><td>A</td></tr>
        </tbody>
    </table>
</body>
</html>

JavaScript文件

document.addEventListener('DOMContentLoaded', function() {
        document.getElementById("idback").addEventListener("click", zuPopupuser);
        document.getElementById("one").addEventListener("click", sortTable(0));
        document.getElementById("two").addEventListener("click", sortTable(1));
        document.getElementById("three").addEventListener("click", sortTable(2));
});

function zuPopupuser() {
        window.location.href="popupuser.html";
}

function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("idsort");
  switching = true;
  dir = "asc"; 
  while (switching) {
    switching = false;
    rows = table.getElementsByTagName("TR");
    for (i = 1; i < (rows.length - 1); i++) {
      shouldSwitch = false;
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          shouldSwitch= true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          shouldSwitch= true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      switchcount ++;      
    } else {
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}

0 个答案:

没有答案