【问题标题】:Create a Search box to find text on page创建一个搜索框以在页面上查找文本
【发布时间】:2012-09-19 16:04:23
【问题描述】:

我正在尝试仅使用 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.")
    }

}

【问题讨论】:

  • 你这样做是为了挑战它吗?对我来说似乎没有必要,因为大多数浏览器都有内置的查找功能(通常是ctrl+f
  • 我正在为学校的作业做这件事。嗯...作业的一部分

标签: javascript search


【解决方案1】:

嗯,您的部分问题是您过早地终止了 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>'
        }        
    }
}

【讨论】:

  • 好的,我已经解决了这个问题,但我仍然无法将搜索到的单词与页面上的文本匹配。
【解决方案2】:

所以这是一种使用 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>

    祝你有美好的一天。

  • 【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 2020-01-13
      相关资源
      最近更新 更多