Laz*_*ing 1 jquery jquery-ui searchfiltercollection
我有一个包含多个行和列以及一组搜索字段的表.我希望能够显示/隐藏与搜索字段匹配/不匹配的行.每个字段都与表的一列相关.我在这项任务中取得了部分成功,因为过滤是正确完成的(正如你在这里看到的).但是,我想解决两件事.
s1.localeCompare(s2)(链接在这里),但它不起作用.顺便说一下,无需担心大写/小写输入.我实际上在原始代码中处理它,但试图在这里保持简单.
这里的代码:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
table = $("#MI6"); //set table name
search_field = new Object();
///we create it as an object, initially empty
$('.search-key').on('change keyup paste', function () {
search_field['name'] = $( "#name" ).val();
search_field['lastname'] = $("#lastname").val();
search_field['number'] = $("#number").val();
table.find('tr').each(function () {
current_row = $(this); //keep track of the row being checked, iterate through it's cells
var display = 0;
current_row.show();
$(this).find('td').each(function() {
//when we stumble upon the data used as a search criteria
cell_value = $(this).html(); //gets the value of the cell being checked
if (cell_value == search_field[this.id] || search_field[this.id] == '') {
display++;
}
});
if (display < 3) {
current_row.hide(); //if this cell is a match, or we no longer want to use it as a search criteria, the row is displayed
}
});
});
});
</script>
</head>
<body>
<input type="text" id="name" class="search-key" placeholder="name">
<input type="text" id="lastname" class="search-key" placeholder="lastname">
<input type="number" id="number" class="search-key" placeholder="number">
<p></p>
<table id="MI6">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Number</th>
</tr>
<tr>
<td id="name">James</td>
<td id="lastname">Bond</td>
<td id="number">7</td>
</tr>
<tr>
<td id="name">Vesper</td>
<td id="lastname">Lynd</td>
<td id="number">6</td>
</tr>
<tr>
<td id="name">Rene</td>
<td id="lastname">Mathis</td>
<td id="number">5</td>
</tr>
</table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
要回答您的第一个问题,只需使用以下内容省略集合中表格的第一行.not(':first'):
table.find('tr').not(':first')
Run Code Online (Sandbox Code Playgroud)
为了进行部分字符串匹配,您可以使用indexOf().
indexOf()方法返回第一次出现的指定值的调用String对象中的索引,从fromIndex开始搜索.如果未找到该值,则返回-1.
我注意到你可以在标记中复制id,它们必须是唯一的.
通过对标记进行一些小的更改,可以重写您的脚本以使其更具动态性:
<td data-input="name">Rene</td>
<td data-input="lastname">Mathis</td>
<td data-input="number">5</td>
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用data-input相应的目标input.您可以将其与jQuery的filter()方法结合使用以返回匹配的行:
/* $rows = table.find('tr').not(':first') */
$rows.hide().filter(function() {
return $(this).find('td').filter(function() {
var tdText = $(this).text().toLowerCase(),
inputValue = $('#' + $(this).data('input')).val().toLowerCase();
return tdText.indexOf(inputValue) != -1;
}).length == $(this).find('td').length;
}).show();
Run Code Online (Sandbox Code Playgroud)
上面首先隐藏每一行,然后过滤.在那里,每个包含的都td被过滤,将其文本与相应的值进行比较input.如果找到匹配项,td则返回.然后,它td根据该td行中元素的数量检查匹配元素的数量,如果它们相同,则所有字段都包含部分匹配,并返回整行.最后,显示任何匹配的行.
这种方式将允许您添加更多输入和tds,而无需修改代码.您只需要id在输入上设置,并添加对应data-input的td元素.