Jquery搜索过滤器不工作后加载ajax内容

Jquery search filter not work after load ajax content

本文关键字:加载 ajax 内容 工作 搜索 过滤器 Jquery      更新时间:2023-09-26

我有一个示例代码

Search:<input type="search" class="form-control" id="search">
<table id="gwAssignForm"><tbody></tbody></table>

我的jquery:

$(document).ready(function() {
   $.ajax({
      type: "POST",
      url: "content.php",
      data: {},
      async : false,
      success: function(result) {
         $('#gwAssignForm tbody').html(result.html);
      },
      error : function(xhr, status){
         console.log(status);
      },
   });
   var $rows = $('#gwAssignForm 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();
   });
});
在content.php

   <tr>
      <td>Apple</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Grapes</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Orange</td>
      <td>Orange</td>
   </tr> 

加载ajax内容后。我开始搜索,但没有成功。如何解决这个问题?

它不起作用,因为您试图在加载ajax数据之前向$rows添加元素。你只需要在你的keyup函数中声明$rows

只需改变这个-

var $rows = $('#gwAssignForm 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();
});

to this -

$('#search').keyup(function() {
  var $rows = $('#gwAssignForm tbody tr');
  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();
});

由于表数据是动态添加的,$rows将是表中的初始行,因此需要在动态添加表数据后更新$rows

$(document).ready(function() {
   var $rows = $('#gwAssignForm tbody tr');
   $.ajax({
      type: "POST",
      url: "content.php",
      data: {},
      async : false,
      success: function(result) {
         $('#gwAssignForm tbody').html(result.html);
         $rows = $('#gwAssignForm tbody tr');
         // update '$rows' after table content is added
      },
      error : function(xhr, status){
         console.log(status);
      },
   });
   $('#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();
   });
});