我在html输入/搜索栏上有一个Javascript工作块。除了一个问题外,这完全有效:
现在,它按完全匹配过滤。因此,它搜索页面上的div,如果任何div及其子表都匹配,它将从表中删除所有其他行,只留下匹配的行。但目前它与确切的字符串匹配。
这只是一个问题,因为我们的很多项目都在数字之间有一个连字符。因此,如果有人搜索4378-65它会过滤他们需要的东西,但如果他们输入437865,它会隐藏所有东西,因为它在技术上没有找到匹配。
希望是一个简单的修复,但任何帮助都非常感谢。
JS:
<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>
答案 0 :(得分:1)
假定连字符对你来说并不重要(根据你提供的信息它们看起来是这样),基本上你所要做的就是在比较过程中删除连字符,所以它基本上忽略了它们的存在:
var filter = $(this).val().replace("-", "");
// ...
var group_name = $(this).children('h3').text().replace("-", "");
这对你有用吗?
答案 1 :(得分:1)
也许这会有所帮助:
// Raw string where you search
var raw = 'word-1 43-286 234568 1-s23'
// Improved string where hyphen is replaced only in numbers
// Just run your search inside this improved string, not with raw
var improved = raw.replace(/\b([\d]+)\-([\d]+)/g, '$1$2')
// Returns word-1 43286 234568 1-s23
console.log(improved) // so only hyphen in pure number was removed