【发布时间】:2017-11-22 13:57:13
【问题描述】:
我有一个搜索输入字段,其中包含一些连接的 javascript,我将其用作页面上的过滤器。它基本上接受输入并在 h3 标记中搜索名称和描述,然后还搜索一个表(特别是 tbody -> tr),如果一行不包含匹配项,则将其隐藏。
我遇到了表格主体/行内容的一个问题。每行都有一个数字,通常是 6 位数字,4 后有一个连字符,但并非总是如此(1234-56、9876-54 等)。
问题是:如果您搜索带有连字符的数字,它会正确过滤并仅显示该数字,但如果您只键入没有连字符的 6 位数字,它会隐藏所有内容,因为它在技术上没有找到匹配项搜索确切的字符串。
我找到了一些方法来做到这一点,但它们只适用于过滤器变量,但我需要一些帮助,即使它只是一个小的解决方法。基本上,在 tbody/tr 中查找匹配项时,我需要它忽略连字符。因此,无论我输入 123456 还是 1234-56,它都只会显示匹配项为 1234-56 的行。我希望这是有道理的。
Javascript:
<script type = "text/javascript">
$(document).ready(function(){
$("#srch-term").keyup(function(){
//For entered search values
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
var search_regex = new RegExp(filter, "i");
// Loop through the main container as well as the table body and row that contains the match
$(".group-container").each(function(){
//check if filter matches the group name or description
var group_name = $(this).children('h3').text()
var group_description = $(this).children('.uk-text-muted').text()
if(group_name.search(search_regex)>=0 || group_description.search(search_regex)>=0){ // filter matches
$(this).show() // show group
$(this).find("tbody tr").show() // and all children
return // skip tr filtering
}
var no_matches = true
$(this).find("tbody tr").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().replace('Available','').search(search_regex) < 0) {
$(this).hide();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
no_matches = false
}
});
if(no_matches){ // if no tr matched the search either, hide whole group
$(this).hide();
}
});
});
});
</script>
【问题讨论】:
标签: javascript jquery