JQuery tablesorting代码不工作(没有插件)

时间:2018-04-17 17:55:22

标签: javascript jquery html html-table

我正在我的网站上显示一个带有AJAX的表格。我编写了一个JQuery代码,用于在通过AJAX发送表时对其进行排序,并单击<th> - 标记。 (我不想使用插件。不,真的,我不想使用插件!)

这是我的代码:

PHP(index.php):

<form action="query.php" method="get">
    <input type="search" name="query" autofocus="true" autocomplete="off" list="products">
    <datalist id="products">
        <?php
            $sql = "SELECT * FROM products;";

            $result = mysqli_query($con, $sql);

            while ($product = mysqli_fetch_array($result)) {
                echo "<option value=\"" . $product["productname"] . "\">" . $product["price"] . " $</option>";
            }
        ?>
    </datalist>
    <button type="submit">Search</button>
</form>
<div class="result" align="center"></div>

PHP(query.php):

<?php
    include_once "connection.php";

    $query = trim($_GET["query"]);
    $query = mysqli_real_escape_string($con, $query);
    $sql = "SELECT * FROM products WHERE productname LIKE '%$query%' ORDER BY productname;";

    $result = mysqli_query($con, $sql);
    $result_no = mysqli_num_rows($result);

    if ($result_no > 0) {
        echo "<table>";
        echo "<thead>";
        echo "<tr>";
        echo "<th>Product</th>";
        echo "<th>Price</th>";
        echo "<th>Quantity</th>";
        echo "</tr>";
        echo "</thead>";
        echo "<tbody>";

        while ($product = mysqli_fetch_array($result)) {
            echo "<tr class=\"table\"><td align=\"left\">" . $product["productname"] . "</td><td align=\"right\">" . $product["price"] . " $</td><td align=\"right\">" . $product["quantity"] . "</td></tr>";
        }

        echo "</tbody>";
        echo "<tfoot>";

        if ($result_no == 1) {
            echo "<tr><td colspan=\"3\" align=\"center\">" . $result_no . " product found." . "</td></tr>";
        } else {
            echo "<tr><td colspan=\"3\" align=\"center\">" . $result_no . " product found." . "</td></tr>";
        }

        echo "</tfoot>";
        echo "</table>";

    } elseif ($result_no <= 0) {
        echo "<p>No products found.</p>";
    }

    mysqli_close($con);
?>

JQuery的:

$(document).ready(function() {  
    $("form").on("submit", function(event) {
        event.preventDefault();

        var form = $(this);

        $.ajax({
            type: this.method,
            url: this.action,
            data: form.serialize(),
            cache: false,
            success: function(data) {
                $("div.result").html(data);

                $("th").on("click", function() {
                    var column = $(this).index();
                    var tbody = $("tbody");
                    var rows = tbody.find("tr");
                    var dir = $(this).data("dir") || -1;
                    dir *= -1;

                    rows.sort(function(a, b) {
                        var aVal = $($(a).find("td")[column]).text().toLowerCase();
                        var bVal = $($(b).find("td")[column]).text().toLowerCase();
                        return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
                    });

                    $(this).data("dir", dir);

                    tbody.empty();
                    $(rows).appendTo(tbody);
                });
            }
        });
    });
});

connection.php用于连接我的数据库。我使用MySQL和PHPMyAdmin。我的表格是登录数据的“用户”和商店产品的“产品”。

我的问题:表格的第一行总是在错误的地方排序。

3 个答案:

答案 0 :(得分:1)

使用内置的javascript sort功能。

  1. 我从您的示例中提取了相关的排序代码
  2. 我从w3cschools
  3. 抓起了一张示例表
  4. 我修改了js以将排序后的方向存储在标题单元格中。
  5. 我实现了compare函数(请参阅链接的排序文档)。
  6. 我在排序完成时替换了tbody
  7. 编辑:更改了HTML,添加了功能以启用数字排序,而不仅仅是按字母顺序排序。 请注意number类和排序函数中的新if

    &#13;
    &#13;
    $("th").on("click", function() {
      var column = $(this).index();
      var numeric = $(this).hasClass("number"); //this class has been sprinkled to identify numeric sort.
      var bdy = $(this).closest("table").find("tbody");
      var rows = bdy.find("tr");
      var dir = $(this).data("dir") || -1; //default direction is desc
      dir *= -1; //reverse the stored direction
      rows.sort(function(a, b) {
        var aVal = $($(a).find("td")[column]).text().toLowerCase(); //get the text from one row
        var bVal = $($(b).find("td")[column]).text().toLowerCase(); //get the text from row 2
        if (numeric) {  //added to handle numeric columns
          aVal = parseFloat(aVal);
          bVal = parseFloat(bVal);
        }
        return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0; // note the dir value to change direction
      }); //sort the rows by the column content
      bdy.empty(); //empty the body
      $(rows).appendTo(bdy); //put the rows back
      $(this).data("dir", dir); //log the direction
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="table">
      <thead>
        <tr class="table">
          <th class="table">Product</th>
          <th class="table number">Price</th>
          <th class="table number">Quantity</th>
        </tr>
      </thead>
      <tbody>
        <tr class="table">
          <td align="left" class="table">Chainsaw</td>
          <td align="right" class="table">60.00 $</td>
          <td align="right" class="table">1</td>
        </tr>
        <tr class="table">
          <td align="left" class="table">Hammer</td>
          <td align="right" class="table">24.99 $</td>
          <td align="right" class="table">2</td>
        </tr>
        <tr class="table">
          <td align="left" class="table">Nails (25 per Box)</td>
          <td align="right" class="table">9.99 $</td>
          <td align="right" class="table">21</td>
        </tr>
        <tr class="table">
          <td align="left" class="table">Screwdriver</td>
          <td align="right" class="table">29.99 $</td>
          <td align="right" class="table">2</td>
        </tr>
        <tr class="table">
          <td align="left" class="table">Screws (25 per Box)</td>
          <td align="right" class="table">15.00 $</td>
          <td align="right" class="table">26</td>
        </tr>
      </tbody>
      <tfoot>
        <tr class="table">
          <td colspan="3" align="center" class="table">5 products found.</td>
        </tr>
      </tfoot>
    </table>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

  

@FelixRewer,请包含一个示例呈现表,您的问题已使用PHP更新。我相信PHP不是你的问题,而是另一端的HTML。

是的,也许你是对的。所以这里是一个代码片段,其中包含query.php和JQuery tablesorter的输出(我还添加了我的样式,我不认为它是相关的,但如果是,那么它就是。):

&#13;
&#13;
$("th").on("click", function() {
  var column = $(this).index();
  var table = $("table");
  var tbody = table.find("tbody");
  var rows = tbody.find("tr");
  var dir = $(this).data("dir") || -1;
  dir *= -1;

  rows.sort(function(a, b) {
    var aVal = $($(a).find("td")[column]).text().toLowerCase().trim();
    var bVal = $($(b).find("td")[column]).text().toLowerCase().trim();
    return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
  });

  $(this).data("dir", dir);

  tbody.empty();
  $(rows).appendTo(table);
});
&#13;
.table {
  margin: 3vmax;
  border: 1px solid #000000;
  border-collapse: collapse;
  color: #000000;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead>
    <tr class="table">
      <th class="table">Product</th>
      <th class="table">Price</th>
      <th class="table">Quantity</th>
    </tr>
  </thead>
  <tbody>
    <tr class="table">
      <td align="left" class="table">Chainsaw</td>
      <td align="right" class="table">60.00 $</td>
      <td align="right" class="table">1</td>
    </tr>
    <tr class="table">
      <td align="left" class="table">Hammer</td>
      <td align="right" class="table">24.99 $</td>
      <td align="right" class="table">2</td>
    </tr>
    <tr class="table">
      <td align="left" class="table">Nails (25 per Box)</td>
      <td align="right" class="table">9.99 $</td>
      <td align="right" class="table">21</td>
    </tr>
    <tr class="table">
      <td align="left" class="table">Screwdriver</td>
      <td align="right" class="table">29.99 $</td>
      <td align="right" class="table">2</td>
    </tr>
    <tr class="table">
      <td align="left" class="table">Screws (25 per Box)</td>
      <td align="right" class="table">15.00 $</td>
      <td align="right" class="table">26</td>
    </tr>
  </tbody>
  <tfoot>
    <tr class="table">
      <td colspan="3" align="center" class="table">5 products found.</td>
    </tr>
  </tfoot>
</table>
&#13;
&#13;
&#13;

是的,我在这里遇到同样的问题。我已经用我的代码测试了很多,我想可能第一行被排序在错误的位置,因为<tfoot>,但这只是一个假设。

答案 2 :(得分:0)

此主题已关闭。这是我要找的代码:

  1. JavaScript:https://jsfiddle.net/tf4e97w6/#&togetherjs=TGIj8qdzUO
  2. jQuery:https://jsfiddle.net/15ke8Lqv/#&togetherjs=DACQV5mE9F
  3. 代码段:
  4. &#13;
    &#13;
    $(document).ready(function() {
      $("th").on("click", function() {
        var column = $(this).index();
        var table = $("table");
        var tbody = table.find("tbody");
        var rows = tbody.find("tr");
        var dir = $(this).data("dir") || -1;
        dir *= -1;
        $(this).siblings().data("dir", -1);
    
        rows.sort(function(a, b) {
          var aVal = $($(a).find("td")[column]).html().toLowerCase().trim();
          var bVal = $($(b).find("td")[column]).html().toLowerCase().trim();
    
          if ($.isNumeric(aVal.charAt()) && $.isNumeric(bVal.charAt())) {
            aVal = parseFloat(aVal);
            bVal = parseFloat(bVal);
          }
    
          return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
        });
    
        $(this).data("dir", dir);
    
        tbody.empty();
        $(rows).appendTo(table);
      });
    });
    &#13;
    h1 {
      color: #cc1100;
    }
    
    table {
      width: 100%;
    }
    
    table,
    tr,
    td {
      border: 1px solid #000000;
      border-collapse: collapse;
    }
    
    tfoot,
    thead {
      text-align: center;
      background-color: #cccccc;
    }
    
    th:hover {
      cursor: pointer;
    }
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <caption>
        <h1>Tablesorter</h1>
      </caption>
      <thead>
        <tr>
          <th>Month</th>
          <th>Savings</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>January</td>
          <td>$150</td>
        </tr>
        <tr>
          <td>February</td>
          <td>$160</td>
        </tr>
        <tr>
          <td>March</td>
          <td>$240</td>
        </tr>
        <tr>
          <td>April</td>
          <td>$160</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="2">Sum: $710</td>
        </tr>
      </tfoot>
    </table>
    &#13;
    &#13;
    &#13;

    亲切的问候, Felix Rewer。