我正在尝试使用html,css和javascript来创建一个搜索框,它将搜索我的页面中的文本,如果找到匹配的文本,该函数应该突出显示跨度内的文本。
我在网上搜索(和stackoverflow),我无法找到与我的需求相关的答案)
我知道该怎么做,但我在某一点陷入困境。继承了我的代码到目前为止的样子。
<script type="text/javascript">
function init(){
//creates a variable equal to the value entered in the text box
var lookfor = document.getElementById("q").value
//splits the whole page into an array or words
var words = document.body.innerHTML.split(" ");
///loops through the array to get each word
for( var i=0; i<words.length; i++){
}
//This is where I get lost, i dont know how to make it so that what you enter
//in the textbox(lookfor) matches somthing on the page. it will get highlighted. i
//was thinking about using the find object, but im new to javascript and dont know
//how to properly use find yet.
if(lookfor == words[i]) //Find()------
{
'<span class="highlight">' + words + '</span>'
}
else{
alert("Sorry, your search returned no results! Please Try again.")
}
}
答案 0 :(得分:0)
好吧,部分问题是你过早地终止你的for循环。应该看起来更像
<script type="text/javascript">
function init()
{
//creates a variable equal to the value entered in the text box
var lookfor = document.getElementById("q").value
//splits the whole page into an array or words
var words = document.body.innerHTML.split(" ");
///loops through the array to get each word
for( var i=0; i<words.length; i++)
{
//This is where I get lost, i dont know how to make it so that what you enter
//in the textbox(lookfor) matches somthing on the page. it will get highlighted. i
//was thinking about using the find object, but im new to javascript and dont know
//how to properly use find yet.
if(lookfor == words[i]) //Find()------
{
'<span class="highlight">' + words + '</span>'
}
}
}
答案 1 :(得分:0)
所以这里有一种方法可以使用 W3.JS JavaScript 库(我提供了它在 w3schools 浏览器上的存储位置的链接)。要搜索的文本应该在文档标签内。与每个项目的
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<script src="https://www.w3schools.com/lib/w3.js"></script>
<body>
<h2>Filter List</h2>
<p>Search for a name in the input field:</p>
<input oninput="w3.filterHTML('#id01', 'li', this.value)" placeholder="Search for names..">
<ul id="id01">
<li>Some text to search</li>
<li>Some other text to search</li>
</ul>
</body>
</html>
祝您有美好的一天。