我有一个示例代码
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();
});
到此-
$('#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();
});
关于javascript - 加载 ajax 内容后 Jquery 搜索过滤器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32838531/