jquery - 根据表详细信息名称和文本过滤表行
问题描述
jQuery 如何过滤 HTML 表中的行,使用 td 标记中的 name 属性和用户从下拉框中选择的选项值?
这是HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h3>filtering table rows</h3>
<label>filter primary</label>
<select>
<option></option>
<option>Watertown</option>
<option>Rockford</option>
<option>Springfield</option>
<option>Evansville</option>
</select>
<table>
<tr>
<th>ID</th>
<th>primary</th>
<th>secondary</th>
<th>mode</th>
</tr>
<tr>
<td>101</td>
<td name="primary">Watertown</td>
<td name="secondary">Rockford</td>
<td>bus</td>
</tr>
<tr>
<td>102</td>
<td name="primary">Springfield</td>
<td name="secondary">Watertown</td>
<td>car</td>
</tr>
<tr>
<td>103</td>
<td name="primary">Evansville</td>
<td name="secondary">Watertown</td>
<td>bus</td>
</tr>
</table>
</body>
这是我到目前为止在 jQuery 上的内容:
// attach event to select box
$('select').on('change', filter);
// filter function
function filter() {
var selectedOption = $('select').find(':selected').text();
$('td').hide();
$('tr').each(function() {
$.each(this.cells, function() {
// need a way to isolate this.cells (td tags) with name attribute equal to "primary" and text within that td tag equal to selectedOption, then hide that table row
});
});
}
jQuery 还不能工作——我被困在如何隔离所需的行上。
例如,如果用户选择 Watertown 作为主要过滤器,则表格应仅显示 1 行 - 主要列中显示 Watertown 的行。
解决方案
您必须根据您选择的值显示表格数据
更新我给<tr id="tableHeading">
显示表头
再次更新删除<tr id>
并添加tr:first-child
代码以显示表头
$('select').on('change', filter);
// filter function
function filter() {
var selectedOption = $('select').find(':selected').val();
$('tr').each(function(){
if($(this).find('td[name=primary]').text() == selectedOption){
$('tr:first-child').show();
$(this).show();
}else{
$('tr:first-child').show();
$(this).hide();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option></option>
<option>Watertown</option>
<option>Rockford</option>
<option>Springfield</option>
<option>Evansville</option>
</select>
<table>
<tr>
<th>ID</th>
<th>primary</th>
<th>secondary</th>
<th>mode</th>
</tr>
<tr>
<td>101</td>
<td name="primary">Watertown</td>
<td name="secondary">Rockford</td>
<td>bus</td>
</tr>
<tr>
<td>102</td>
<td name="primary">Springfield</td>
<td name="secondary">Watertown</td>
<td>car</td>
</tr>
<tr>
<td>103</td>
<td name="primary">Evansville</td>
<td name="secondary">Watertown</td>
<td>bus</td>
</tr>
</table>
推荐阅读
- oracle - 休眠查询将逗号分隔的字符串与列表进行比较
- android - 点之间的 ArcGISRuntime 箭头
- java - 为什么android仍然使用Java 8?
- python - 如何比较不同的 json 显示,如 git diff
- java - 使用py4j将python列表转换为java数组
- ansible - 根据符号链接设置 Ansible 事实
- javascript - 单击按钮时如何跳转到另一个 HTML 页面
- php - 如果未选择属性按钮上的红色轮廓,如何在属性按钮上显示错误?
- c# - 数组中的元素可以引用数组吗?
- amazon-web-services - 恢复 AWS 账户以删除正在运行的服务