【问题标题】:JQuery tablesorting code not working (no plugin)JQuery 表格排序代码不起作用(没有插件)
【发布时间】:2018-09-27 19:16:11
【问题描述】:

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

这是我的代码:

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。我的表是登录数据的“用户”和商店产品的“产品”。

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

【问题讨论】:

  • 什么是数据?如果您没有使用 tablesorter 插件,请删除该标签。
  • 什么不起作用?你的预期输出是什么?我们没有简单的方法来针对实际数据运行它,因此无法判断它出了什么问题。

标签: javascript jquery html html-table


【解决方案1】:

使用内置的 javascript sort 函数。

  1. 我从您的示例中提取了相关的排序代码
  2. 我从w3cschools 获取了一个样本表
  3. 我修改了js 以将排序的方向存储在标题单元格中。
  4. 我实现了一个compare 函数(请参阅链接的排序文档)。
  5. 排序完成后,我替换了tbody

编辑:更改 HTML,添加功能以启用数字排序,而不仅仅是按字母顺序。 注意排序函数中的number 类和新的if

$("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
});
<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>

【讨论】:

  • 谢谢,但它似乎不起作用。如果我运行此代码,第一行是错误的。也许是因为我桌子上的美元符号?
  • Felix 如果您提供了任何 HTML,那么我们也许可以帮助您解决问题。这只是按字母顺序比较单元格。
  • 我添加了我的代码。 PS:我修改了你的代码,不是为了让它更有用,只是为了好看。
  • @FelixRewer,请包含一个示例渲染表,您的问题已使用您的 PHP 进行了更新。我相信 PHP 不是你的问题,而是另一端出现的 HTML。
【解决方案2】:

@FelixRewer,请提供一个示例渲染表,您的问题已使用您的 PHP 进行了更新。我相信 PHP 不是你的问题,而是另一端出现的 HTML。

是的,也许你是对的。所以这是一个带有 query.php 和 JQuery 表排序器输出的代码 sn-p(我还添加了我的样式,我认为它不相关,但如果是的话,就在这里。):

$("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);
});
.table {
  margin: 3vmax;
  border: 1px solid #000000;
  border-collapse: collapse;
  color: #000000;
}
<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>

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

【讨论】:

  • 我更新了我的答案,包括按数字排序而不仅仅是按字母顺序排序。
【解决方案3】:

此主题已关闭。这是我正在寻找的代码:

  1. JavaScript:https://jsfiddle.net/tf4e97w6/#&togetherjs=TGIj8qdzUO
  2. jQuery: https://jsfiddle.net/15ke8Lqv/#&togetherjs=DACQV5mE9F
  3. 代码 sn-p:

$(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);
  });
});
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;
}
<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>

诚挚的问候, 费利克斯·雷尔。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2016-08-31
    • 2017-10-11
    • 2017-11-06
    相关资源
    最近更新 更多