我使用 jQuery 从头开始编写了一个搜索功能,以满足特定需求。它从 <span>
中搜索数据的 <div>
然后隐藏 <div>
如果它与文本框中的字符串不匹配。
我遇到的问题是它可以识别字符串但不能识别第一个字符。它还区分大小写,这不是我想要包含的功能。
//Grab ID of current recordContainer
var currentID = $(this).attr('id');
// Add hash tag so it can be used as an ID call
var currentID2 = ("#" + currentID);
//Grab data from author span in current recordContainer
var currentAuthor = $(this).children('span.listLeadAuthor').text();
//If current author matches anything in the search box then keep it visible
if (currentAuthor.search(searchBox1) > 0)
{
$(currentID2).show();
count++;
}
//If search box is empty keep it visible
else if (searchBox1 === "")
{
$(currentID2).show();
}
最佳答案
问题是您的 if 语句忽略了第一个字符,因为第一个字符位于索引 0。
if (currentAuthor.search(searchBox1) > 0)
应该是:
if (currentAuthor.search(searchBox1) >= 0)
如果您需要区分大小写,则需要应用 toUpperCase()
或 toLowerCase()
。
if (currentAuthor.ToUpperCase().search(searchBox1.toUpperCase()) >= 0)
关于javascript - 为什么我的搜索功能只在我错过第一个字符时才匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15634074/