如何只使用JS給靜態(tài)頁面網站添加站內全局搜索功能
背景
靜態(tài)頁面通常由HTML、CSS 和 JavaScript 等靜態(tài)文件組成,這些文件在服務器上不會動態(tài)生成或修改,所以加載速度通常比較快。也利于搜索引擎的抓取,適合用于展示固定內容的網站,如企業(yè)官方網站、產品介紹頁、博客文章等。
為網頁添加搜索模塊的第三方網站有不少,首先我嘗試了一下谷歌的站內搜索,讓人比較痛苦的一個是前幾行都是谷歌廣告,而且還去不掉,還有一點就是搜索結果只能展示谷歌收錄的頁面,比如我網站加上小語種至少有幾千個頁面了,但是谷歌實際收錄的頁面只有幾百,也就是說百分之80-90的結果都展示不出來,這兩點就讓人很絕望了,不得不另謀他路。
解決方案
從網上摸索了一圈,終于找到了一種比較簡單的使用 js 實現(xiàn)的搜索功能,經過幾番倒騰終于可以成功復現(xiàn)。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Search Example</title> <style> #searchInput { margin-bottom: 10px; } .urlset li { display: none; } .pagination { margin-top: 10px; } </style> </head> <body> <input type="text" id="searchInput" placeholder="輸入關鍵字"> <ul class="urlset"> <li class="aurl"><a rel="external nofollow" data-lastfrom="" title="Peptide Expert & Quality Proteins & Ubiquitins factory">Peptide Expert & Quality Proteins & Ubiquitins factory</a></li> <li class="aurl"><a rel="external nofollow" data-lastfrom="" title="chat with us">chat with us</a></li> <li class="aurl"><a rel="external nofollow" data-lastfrom="" title="China Hefei KS-V Peptide Biological Technology Co.Ltd company profile">China Hefei KS-V Peptide Biological Technology Co.Ltd company profile</a></li> <!-- 此處省略一萬條鏈接 --> </ul> <script> document.getElementById('searchInput').addEventListener('input', function () { var searchKeyword = this.value.toLowerCase(); var links = document.querySelectorAll('.urlset a'); links.forEach(function (link) { var title = link.getAttribute('title').toLowerCase(); var url = link.getAttribute('href').toLowerCase(); if (title.includes(searchKeyword) || url.includes(searchKeyword)) { link.parentNode.style.display = 'block'; } else { link.parentNode.style.display = 'none'; } }); }); </script> </body> </html>
效果如下:
到這里我們已經初步完成了一個簡陋的搜索功能,頁面不多的個人博客、小型企業(yè)站其實已經可以拿來用了。但是當我們頁面比較多,比如有300+頁面,那么上面光一個搜索功能就需要接近400行的代碼,每個頁面都放入這400行代碼,直接300*400,加重服務器的負擔,影響頁面加載速度,維護起來也十分困難。
優(yōu)化方法
首先我們將這些鏈接+標題都放入一個xml中,格式如下:
<?xml version="1.0" encoding="UTF-8"?> <links> <link> <url>https://www.ks-vpeptide.com/</url> <title>Peptide Expert & Quality Proteins & Ubiquitins factory</title> </link> <link> <url>https://www.ks-vpeptide.com/webim/webim_tab.html</url> <title>chat with us</title> </link> <link> <url>https://www.ks-vpeptide.com/aboutus.html</url> <title>China Hefei KS-V Peptide Biological Technology Co.Ltd company profile</title> </link> <!-- 此處省略一萬條<link></link> --> <link> <url>https://www.ks-vpeptide.com/buy-h4k12ac.html</url> <title>Buy h4k12ac, Good quality h4k12ac manufacturer</title> </link> <link> <url>https://www.ks-vpeptide.com/contactnow.html</url> <title>Send your inquiry directly to us</title> </link> </links>
頁面較多的可以用工具生成xml,我這保存了一個可以免費生成網站站點地圖的工具:https://sitemap.zhetao.com/
該工具有一點較好的是它生成的格式有多種供選擇,缺點就是一個站點180天只能生成一次,挺難受的。
到這里我們把之前的代碼修改一下,
<body> <!-- hysousuo --> <input type="text" id="searchInput" placeholder="輸入關鍵字"> <ul class="urlset"> <!-- 鏈接將在這里動態(tài)加載 --> </ul> <script> document.getElementById('searchInput').addEventListener('input', function () { var searchKeyword = this.value.toLowerCase(); <!-- your_links.xml 換成你的 xml 名稱 --> fetch('your_links.xml') .then(response => response.text()) .then(data => { var parser = new DOMParser(); var xmlDoc = parser.parseFromString(data, 'application/xml'); var links = xmlDoc.querySelectorAll('link'); links.forEach(function (link) { var url = link.querySelector('url').textContent.toLowerCase(); var title = link.querySelector('title').textContent.toLowerCase(); var li = document.createElement('li'); li.className = 'aurl'; li.innerHTML = `<a href="${url}" rel="external nofollow" rel="external nofollow" data-lastfrom="" title="${title}">${title}</a>`; document.querySelector('.urlset').appendChild(li); if (title.includes(searchKeyword) || url.includes(searchKeyword)) { li.style.display = 'block'; } else { li.style.display = 'none'; } }); }) .catch(error => console.error('Error fetching XML:', error)); }); </script> </body>
改完之后我發(fā)現(xiàn)搜索結果出不來了,看了下控制臺的報錯,原來是瀏覽器的同源策略導致的,該策略要求網頁中使用的所有腳本(包括 JavaScript、CSS、圖片等)都必須來自同一源(協(xié)議、域名和端口)。
在這種情況下,我的頁面是通過 file:/// 協(xié)議打開的,而 XML 文件路徑是絕對路徑 C:/Users/18363/Documents/HBuilderProjects/demo/your links.xml。這導致了跨源請求,因為 file:/// 協(xié)議和 C: 協(xié)議不同。
解決方法:將文件上傳至服務器中運行。試了一下果然好了
在加入我們網站時我們需要將搜索結果置于頁面頂層(指的是里外的最外層),所以還需要再加一段CSS,最終完整代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Search Example</title> <style> #searchInput { margin-bottom: 10px; } .searchResults { position: absolute; top: 60px; /* 調整彈窗的垂直位置 */ left: 10px; z-index: 999; /* 確保彈窗在最上層 */ background-color: white; border: 1px solid #ccc; padding: 10px; display: none; } .searchResults li { list-style-type: none; } </style> </head> <body> <!-- hysousuo --> <!-- 搜索框 --> <form> <input type="text" id="searchInput" placeholder="Search Keywords or Catalog Number"> </form> <!-- 搜索結果 --> <ul class="searchResults"> <!-- 搜索結果將會動態(tài)加載到這里 --> </ul> <!-- JavaScript 代碼 --> <script> const searchInput = document.getElementById('searchInput'); const searchResultsContainer = document.querySelector('.searchResults'); searchInput.addEventListener('input', function () { const searchKeyword = this.value.toLowerCase(); // 清空之前的搜索結果 searchResultsContainer.innerHTML = ''; if (searchKeyword.trim() === '') { // 如果搜索關鍵字為空,隱藏彈窗并返回 searchResultsContainer.style.display = 'none'; return; } fetch('https://ks-vpeptide.haiyong.site/your_links.xml') .then(response => response.text()) .then(data => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(data, 'application/xml'); const links = xmlDoc.querySelectorAll('link'); let hasResults = false; links.forEach(link => { const url = link.querySelector('url').textContent.toLowerCase(); const title = link.querySelector('title').textContent.toLowerCase(); if (title.includes(searchKeyword) || url.includes(searchKeyword)) { const li = document.createElement('li'); li.className = 'aurl'; li.innerHTML = `<a href="${url}" rel="external nofollow" rel="external nofollow" data-lastfrom="" title="${title}">${title}</a>`; searchResultsContainer.appendChild(li); hasResults = true; } }); // 根據搜索結果顯示或隱藏彈窗 searchResultsContainer.style.display = hasResults ? 'block' : 'none'; }) .catch(error => console.error('Error fetching XML:', error)); }); // 監(jiān)聽輸入框失去焦點事件,隱藏搜索結果彈窗 searchInput.addEventListener('blur', function () { // 使用 setTimeout 確保點擊搜索結果時能觸發(fā)鏈接 setTimeout(() => { searchResultsContainer.style.display = 'none'; }, 200); }); </script>
最終實現(xiàn)效果:
樣式還有點奇怪,還需要再調整一下,其他沒什么問題了,如果大家有需要幫助,可以在下方評論區(qū)告訴我,有什么其他添加搜索功能的好辦法也可以分享出來給大家參考。
總結
本文介紹了靜態(tài)頁面添加搜索功能的問題、解決方案和優(yōu)化方法,通過實例演示了如何利用 JavaScript 動態(tài)加載 XML 中的數(shù)據實現(xiàn)搜索功能,為需要在靜態(tài)頁面中添加搜索功能的讀者提供一定價值的參考。
到此這篇關于如何只使用JS給靜態(tài)頁面網站添加站內全局搜索功能的文章就介紹到這了,更多相關JS靜態(tài)頁面網站站內全局搜索內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript搜索框點擊文字消失失焦時文本出現(xiàn)
這篇文章主要介紹了javascript實現(xiàn)搜索框點擊文字消失失焦時文本出現(xiàn)的效果,示例代碼如下,大家可以看看2014-09-09JavaScript用document.write()輸出換行的示例代碼
這篇文章主要介紹了JavaScript用document.write()輸出換行的示例代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11