您好,登錄后才能下訂單哦!
這篇文章給大家介紹使用jQuery怎么實現一個頁面關鍵字搜索功能,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
具體代碼:
<html> <head> <title>Search</title> <style type="text/css"> p { border:1px solid black;width:500px;padding:5px;} .highlight { background-color:yellow; } </style> </head> <body> <form> <p> I consider that a man's brain originally is like a little empty attic, and you have to stock it with such furniture as you choose. A fool takes in all the lumber of every sort that he comes across, so that the knowledge which might be useful to him gets crowded out, or at best is jumbled up with a lot of other things, so that he has a difficulty in laying his hands upon it. </p> <p> I consider that a man's brain originally is like a little empty attic, and you have to stock it with such furniture as you choose. A fool takes in all the lumber of every sort that he comes across, so that the knowledge which might be useful to him gets crowded out, or at best is jumbled up with a lot of other things, so that he has a difficulty in laying his hands upon it. </p> <p> I consider that a man's brain originally is like a little empty attic, and you have to stock it with such furniture as you choose. A fool takes in all the lumber of every sort that he comes across, so that the knowledge which might be useful to him gets crowded out, or at best is jumbled up with a lot of other things, so that he has a difficulty in laying his hands upon it. </p> <input type="text" id="text"/> <input type="button" id="search" value="Search"/> <input type="button" id="clear" value="Clear"/> </form> <script type="text/javascript" src="../jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#search').click(highlight);//點擊search時,執行highlight函數; $('#clear').click(clearSelection);//點擊clear按鈕時,執行clearSelection函數; function highlight() { clearSelection();//先清空一下上次高亮顯示的內容; var searchText = $('#text').val();//獲取你輸入的關鍵字; var regExp = new RegExp(searchText, 'g');//創建正則表達式,g表示全局的,如果不用g,則查找到第一個就不會繼續向下查找了; $('p').each(function()//遍歷文章; { var html = $(this).html(); var newHtml = html.replace(regExp, '<span class="highlight">'+searchText+'</span>');//將找到的關鍵字替換,加上highlight屬性; $(this).html(newHtml);//更新文章; }); } function clearSelection() { $('p').each(function()//遍歷 { $(this).find('.highlight').each(function()//找到所有highlight屬性的元素; { $(this).replaceWith($(this).html());//將他們的屬性去掉; }); }); } }); </script> </body> </html>
關于使用jQuery怎么實現一個頁面關鍵字搜索功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。