您好,我使用输入框对 div 进行基本文本搜索,但只有输入准确的完整单词才能使其工作,我将如何修改此代码以适用于子字符串,例如如果我输入 Test,我想同时返回 Test 和 Test2,或者只是 T 应该返回两者等等?
//search site for pages
function search_sitemap() {
let input = document.getElementById('searchbar').value
input=input.toLowerCase();
let x = document.getElementsByClassName('pages');
var urls = [];
for (i = 0; i < x.length; i++) {
// make an array of strings
var words = x[i].innerHTML.toLowerCase().split(",");
if (!words.includes(input)) {
x[i].style.display="none";
}
else {
x[i].style.display = "block";
urls.push(x[i].href);
}
}
return urls;
}
</script>
<!DOCTYPE html>
<html>
<head></head>
<body>
<header></header>
<!--searchbar-->
<button class="searchbtn"><img src="Images\search.png" id="s-icon">
<div id='searchlist'>
<a class="pages" href="test.html" style="display:none;">Test</a></li>
<a class="pages" href="test2.html" style="display:none;">Test2</a></li>
<a class="pages" href="best.html" style="display:none;">Best</a></li>
<a class="pages" href="rest.html" style="display:none;">Rest</a></li>
</div>
</button>
<div class="searchbar">
<input type="text" id="searchbar" onkeyup="search_sitemap()" placeholder="" value="Search.." maxlenght="25" autocomplete="off" onMouseDown="active();" onBlur="inactive()" />
</div>
</div>
</body>
</html>
最佳答案
您可以检查是否某些单词以搜索开头:
words.some(word => word.startsWith(input))
关于Javascript 子字符串搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57397747/