我刚刚设法使这个表过滤器工作,但到目前为止它只过滤一列(硬编码的)。我想防止硬编码并使过滤器同时在所有列上工作。任何人都可以帮助我解决这个问题吗?
我尝试使用双重forloop循环遍历所有6列,但这似乎不起作用。
JQuery的
$(document).ready(function () {
$('#myInput').keyup(function() {
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[6]; // This is the hardcoded column
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
});
});
HTML:
<table id="myTable">
<tr class="header">
<th>Id</th>
<th>Activity Name</th>
<th>Description</th>
<th>Capacity</th>
<th>Start Time</th>
<th>End Time</th>
<th>Main Event</th>
<th>Location</th>
<th>Price</th>
<th> </th>
<th> </th>
</tr>
@foreach (Activity a in Model.ActivitiesList)
{
if (a != null)
{
<tr>
<td>@a.Id</td>
<td>@a.Name</td>
<td>@a.Description</td>
<td>@a.Capacity</td>
<td>@a.StartTime</td>
<td>@a.EndTime</td>
<td>@Model.GetSubjectById(a.SubjectId)</td>
<td>@Model.GetLocationById(a.LocationId)</td>
<td>@a.Price</td>
<td>
@Html.ActionLink(linkText: "Edit",
actionName: "EditEvent",
controllerName: "Dashboard",
routeValues: new { id = a.Id, subjectId = a.SubjectId },
htmlAttributes: new { @class = "icon-1 info-tooltip", @Title = "Edit" })
</td>
<td>
@Html.ActionLink(
"Remove",
"RemoveEvent",
new { id = a.Id, subjectId = a.SubjectId },
new { onclick = "return confirm('Are you sure you wish to delete this activity?');" }
)
</td>
</tr>
}
else
{
continue;
}
}
答案 0 :(得分:1)
你绝对应该考虑使用jqGrid或datatables(如注释中所建议的那样),但由于你已经使用了jQuery,对于你当前的代码,这应该可行:
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
var foundCells = $(tr[i]).find("td:contains(" + filter + ")");
if (foundCells.length == 0) {
$(tr[i]).hide();
} else {
$(tr[i]).show();
}
}
请注意,这会执行区分大小写的搜索。如果您需要不区分大小写,请查看this answer如何使用不区分大小写的:contains
。