【问题标题】:Tweaking jQuery search for table调整 jQuery 搜索表
【发布时间】:2018-04-08 22:15:39
【问题描述】:

我有一个表格搜索功能,我想调整它以仅在标题列中查找匹配项。并隐藏所有与标题文本不匹配的项目。我的代码

JS

var $rows = $('#table tbody tr');
$('#search').keyup(function () {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

    $rows.show().filter(function () {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
    }).hide();
});

HTML

         <table id="table" class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>Handlingar</th>
                    <th>Title</th>  <-----This column----
                    <th>Pris i kr</th>
                    <th>Skapad</th>
                    <th>Kategori</th>
                </tr>
            </thead>
            <tbody>
                @foreach (BuyAndSellAppWeb.Models.Advertisment objProduct in Model)
                {
                    <tr>
                        @if (objProduct.SellerToken)
                        {
                            <td>

                                @Html.ActionLink("Ändra", "Edit", new { id = objProduct.ID }) | @Html.ActionLink("Radera", "DeleteItem", new { id = objProduct.ID }) | @Html.ActionLink("Detaljer", "Details", new { id = objProduct.ID })

                        </td>
                        }
                        else
                        {
                            <td>
                                @Html.ActionLink("Detaljer", "Details", new { id = objProduct.ID })
                            </td>
                        }
                        <td>@objProduct.ProductTitle</td>
                        <td>@objProduct.Price kr</td>
                        <td>@objProduct.Created.ToString("yyyy/MMM/dd")</td>
                        <td id="category">@objProduct.Category</td>
                    </tr>
                }
            </tbody>
        </table>

尝试了很多不同的组合,但都没有奏效。

【问题讨论】:

  • 您的代码对我来说运行良好
  • 是的,但它会搜索所有列。我想缩小范围,只从标题库中找到匹配项。

标签: jquery search html-table


【解决方案1】:

在你的 js 中试试这个。希望有效

$(document).ready(function() {
      var $rows = $('#table tbody tr');
      $('#search').keyup(function () {
          var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

          $rows.show().filter(function () {
              var text = $($(this).find('td')[1]).text().replace(/\s+/g, ' ').toLowerCase();
              return !~text.indexOf(val);
          }).hide();
      });
});

【讨论】:

  • 我已经修改了var text = $($(this).find('td')[1]).text().replace(/\s+/g, ' ').toLowerCase(); line
  • 自己解决了这样的问题:var text = $(this).children(":eq(" + "1" + ")").text().replace(/\s+/g, ' ').toLowerCase();Witch one 你认为更好吗?
  • 顺便说一句
  • 在这种情况下两者都很好,因为只有 5 个 可供搜索。你可以使用任何你想要的:)
  • “试试这个” 没有解释有什么不同或为什么有帮助
猜你喜欢
相关资源
最近更新 更多
热门标签