如何只使用JS給靜態(tài)頁面網(wǎng)站添加站內(nèi)全局搜索功能
背景
靜態(tài)頁面通常由HTML、CSS 和 JavaScript 等靜態(tài)文件組成,這些文件在服務(wù)器上不會動態(tài)生成或修改,所以加載速度通常比較快。也利于搜索引擎的抓取,適合用于展示固定內(nèi)容的網(wǎng)站,如企業(yè)官方網(wǎng)站、產(chǎn)品介紹頁、博客文章等。
為網(wǎng)頁添加搜索模塊的第三方網(wǎng)站有不少,首先我嘗試了一下谷歌的站內(nèi)搜索,讓人比較痛苦的一個是前幾行都是谷歌廣告,而且還去不掉,還有一點(diǎn)就是搜索結(jié)果只能展示谷歌收錄的頁面,比如我網(wǎng)站加上小語種至少有幾千個頁面了,但是谷歌實(shí)際收錄的頁面只有幾百,也就是說百分之80-90的結(jié)果都展示不出來,這兩點(diǎn)就讓人很絕望了,不得不另謀他路。

解決方案
從網(wǎng)上摸索了一圈,終于找到了一種比較簡單的使用 js 實(shí)現(xiàn)的搜索功能,經(jīng)過幾番倒騰終于可以成功復(fù)現(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="輸入關(guān)鍵字">
<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>
效果如下:

到這里我們已經(jīng)初步完成了一個簡陋的搜索功能,頁面不多的個人博客、小型企業(yè)站其實(shí)已經(jīng)可以拿來用了。但是當(dāng)我們頁面比較多,比如有300+頁面,那么上面光一個搜索功能就需要接近400行的代碼,每個頁面都放入這400行代碼,直接300*400,加重服務(wù)器的負(fù)擔(dān),影響頁面加載速度,維護(hù)起來也十分困難。
優(yōu)化方法
首先我們將這些鏈接+標(biāo)題都放入一個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,我這保存了一個可以免費(fèi)生成網(wǎng)站站點(diǎn)地圖的工具:https://sitemap.zhetao.com/

該工具有一點(diǎn)較好的是它生成的格式有多種供選擇,缺點(diǎn)就是一個站點(diǎn)180天只能生成一次,挺難受的。

到這里我們把之前的代碼修改一下,
<body>
<!-- hysousuo -->
<input type="text" id="searchInput" placeholder="輸入關(guān)鍵字">
<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)搜索結(jié)果出不來了,看了下控制臺的報錯,原來是瀏覽器的同源策略導(dǎo)致的,該策略要求網(wǎng)頁中使用的所有腳本(包括 JavaScript、CSS、圖片等)都必須來自同一源(協(xié)議、域名和端口)。

在這種情況下,我的頁面是通過 file:/// 協(xié)議打開的,而 XML 文件路徑是絕對路徑 C:/Users/18363/Documents/HBuilderProjects/demo/your links.xml。這導(dǎo)致了跨源請求,因?yàn)?file:/// 協(xié)議和 C: 協(xié)議不同。
解決方法:將文件上傳至服務(wù)器中運(yùn)行。試了一下果然好了

在加入我們網(wǎng)站時我們需要將搜索結(jié)果置于頁面頂層(指的是里外的最外層),所以還需要再加一段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; /* 調(diào)整彈窗的垂直位置 */
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>
<!-- 搜索結(jié)果 -->
<ul class="searchResults">
<!-- 搜索結(jié)果將會動態(tài)加載到這里 -->
</ul>
<!-- JavaScript 代碼 -->
<script>
const searchInput = document.getElementById('searchInput');
const searchResultsContainer = document.querySelector('.searchResults');
searchInput.addEventListener('input', function () {
const searchKeyword = this.value.toLowerCase();
// 清空之前的搜索結(jié)果
searchResultsContainer.innerHTML = '';
if (searchKeyword.trim() === '') {
// 如果搜索關(guān)鍵字為空,隱藏彈窗并返回
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;
}
});
// 根據(jù)搜索結(jié)果顯示或隱藏彈窗
searchResultsContainer.style.display = hasResults ? 'block' : 'none';
})
.catch(error => console.error('Error fetching XML:', error));
});
// 監(jiān)聽輸入框失去焦點(diǎn)事件,隱藏搜索結(jié)果彈窗
searchInput.addEventListener('blur', function () {
// 使用 setTimeout 確保點(diǎn)擊搜索結(jié)果時能觸發(fā)鏈接
setTimeout(() => {
searchResultsContainer.style.display = 'none';
}, 200);
});
</script>
最終實(shí)現(xiàn)效果:

樣式還有點(diǎn)奇怪,還需要再調(diào)整一下,其他沒什么問題了,如果大家有需要幫助,可以在下方評論區(qū)告訴我,有什么其他添加搜索功能的好辦法也可以分享出來給大家參考。
總結(jié)
本文介紹了靜態(tài)頁面添加搜索功能的問題、解決方案和優(yōu)化方法,通過實(shí)例演示了如何利用 JavaScript 動態(tài)加載 XML 中的數(shù)據(jù)實(shí)現(xiàn)搜索功能,為需要在靜態(tài)頁面中添加搜索功能的讀者提供一定價值的參考。
到此這篇關(guān)于如何只使用JS給靜態(tài)頁面網(wǎng)站添加站內(nèi)全局搜索功能的文章就介紹到這了,更多相關(guān)JS靜態(tài)頁面網(wǎng)站站內(nèi)全局搜索內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
設(shè)置checkbox為只讀(readOnly)的兩種方式
設(shè)置checkbox為只讀的方法有很多,在本文為大家詳細(xì)介紹下兩種比較實(shí)用的方法,感興趣的朋友不要錯過2013-10-10
微信小程序適配iphoneX的實(shí)現(xiàn)方法
這篇文章主要介紹了微信小程序適配iphoneX的實(shí)現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09
javascript搜索框點(diǎn)擊文字消失失焦時文本出現(xiàn)
這篇文章主要介紹了javascript實(shí)現(xiàn)搜索框點(diǎn)擊文字消失失焦時文本出現(xiàn)的效果,示例代碼如下,大家可以看看2014-09-09
JavaScript數(shù)據(jù)類型學(xué)習(xí)筆記
這篇文章主要針對JavaScript數(shù)據(jù)類型整理的學(xué)習(xí)筆記,分享給大家,感興趣的小伙伴們可以參考一下2016-01-01
復(fù)制小說文本時出現(xiàn)的隨機(jī)亂碼的去除方法
想把小說復(fù)制下來慢慢看,卻發(fā)現(xiàn)復(fù)制到記事本里出現(xiàn)一大堆亂七八糟的東西,很是不爽。于是就想了個簡單的辦法把它干掉了。2010-09-09
JavaScript用document.write()輸出換行的示例代碼
這篇文章主要介紹了JavaScript用document.write()輸出換行的示例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
JS實(shí)現(xiàn)獲取自定義屬性data值的方法示例
這篇文章主要介紹了JS實(shí)現(xiàn)獲取自定義屬性data值的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了javascript針對自定義屬性data的相關(guān)操作技巧,需要的朋友可以參考下2018-12-12
利用JS實(shí)現(xiàn)二叉樹遍歷算法實(shí)例代碼
眾所周知javascript語言中只提供了幾種基本類型的數(shù)據(jù)類型,而二叉樹是一種數(shù)據(jù)結(jié)構(gòu),在一些查詢等操作中能提供較好的性能,這篇文章主要給大家介紹了關(guān)于利用JS實(shí)現(xiàn)二叉樹遍歷算法的相關(guān)資料,需要的朋友可以參考下2021-11-11
javascript &&和||運(yùn)算法的另類使用技巧
一直以為 && 和 || 這兩個偉大的運(yùn)算法只能在判斷表達(dá)式使用,也就是常在if語句使用,原來錯了,它還可以運(yùn)用在簡化選擇性執(zhí)行語句的操作,有點(diǎn)拗口,簡單點(diǎn)也就是:操作執(zhí)行某條語句,不執(zhí)行某條語句。2009-11-11

