我正在进行实时搜索,我希望表中与筛选器不匹配的元素淡出以及匹配显示的那些元素。但是,这不起作用:
使用Javascript:
$("#filter").keyup(function () {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'Search',
success:
function (result) {
console.log(result.Books);
var filter = $("#filter").val();
console.log(filter);
// Loop through each row of the table
result.Books.forEach(
(function (book, index) {
console.log(index);
var i = index;
var title = book.Title;
console.log(title);
if (title.search(new RegExp(filter, "i")) < 0) {
$(table tr).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(table tr).show();
}
})
)
}
});
});
我的HTML:
<table id="tableCurrentRented" class="table">
<thead>
<tr class="webgrid-header">
<th scope="col">
<a href="/AuthenticatedUser/SearchBooks?sort=Title&sortdir=ASC">Title</a> </th>
<th scope="col">
<a href="/AuthenticatedUser/SearchBooks?sort=Author&sortdir=ASC">Author</a> </th>
<th scope="col">
Available </th>
<th scope="col">
Rent </th>
</tr>
</thead>
<tbody>
<tr class="webgrid-row-style">
<td>A Christmas Carol</td>
<td>Charles Dickens</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="10" data-title="A Christmas Carol">Yes</button></td>
</tr>
<tr class="webgrid-alternating-row">
<td>aaa</td>
<td>Aaa</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="11" data-title="aaa">Yes</button></td>
</tr>
<tr class="webgrid-row-style">
<td>Charlotte Bronte</td>
<td>Jane Eyre</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="7" data-title="Charlotte Bronte">Yes</button></td>
</tr>
<tr class="webgrid-alternating-row">
<td>Emma</td>
<td>Jane Austen</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="4" data-title="Emma">Yes</button></td>
</tr>
<tr class="webgrid-row-style">
<td>Far From The Madding Crowd</td>
<td>Thomas Hardy</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="2" data-title="Far From The Madding Crowd">Yes</button></td>
</tr>
</tbody>
</table>
正如您将注意到的,该功能是将模型的标题与过滤器进行比较。如果匹配,则应显示该模型的行。如果它不匹配,它应该淡出。知道我在这里做错了吗?
答案 0 :(得分:0)
应该是这样的:
$("table tr").fadeOut();
和
$("table tr").show();
而不是$(table tr).show();
。你错过了双引号来使它成为字符串。
答案 1 :(得分:0)
当您尝试过滤现有结果时,我认为您不需要服务器端调用。而你的逻辑也不清楚。您尝试过str.search,但如果该结果匹配,则您的代码不会保留该特定的tr。
您可以尝试此代码
$(document).on('change', '#filter', function()){
var filter_regex = new RegExp($( (this).val() + '').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&"), "i" );
$('#tableCurrentRented tbody tr').each(function(){
var val = $(this)find('td:first').val();
if( ( val.search(filter_regex)) <0 ){
$(this).hide();
}else{
$(this).show();
}
})
}