使用 FlexSearch 创建搜索模板 - 快速搜索您的文章内容
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>使用 FlexSearch 创建搜索模板</title>
<script src='https://cdn.jsdelivr.net/npm/flexsearch/dist/flexsearch.min.js'></script>
<script>
// 加载数据
const data = JSON.parse(`[['没有农药化肥,这颗羊奶果无疑是最自然的果实','2023年03月03日','/article/2023/0318.html','2023年02月16日,我发现三年前所种植的羊奶果树开始结果了,这是三年来的第一次丰收。身为一名农夫,能够看到自己种植的作物顺利成长,获得丰收,是非常开心的一件事情。 '],['三岁的玥玥与年长孩子玩耍中的困难与机遇','2023年03月03日','/article/2023/0317.html','时间大概还在是在2021年,具体日期已经不记得了。'],['与小朋友一起探索大自然——捞鱼之旅','2023年03月03日','/article/2023/0316.html','时间大概是在2021年,具体日期已经不记得了。 '],['茜茜第一次主动把垃圾给我','2023年03月03日','/article/2023/0315.html','2023年02月18日这一天,玥玥一来到我家,就要我带着她去找黄生。更优秀。我一直都相信她,她可以好这一切的。(内容整理日期:2023年03月15日,作者:黄胜丰,地址:广西壮族自治区富川瑶族自治县新华乡上坝村。) '],['玥玥在篮球场把自己吃零食产生的垃圾丢到垃圾桶','2023年03月03日','/article/2023/0314.html','也是在2023年02月12日这一天 ']]`);
<pre><code> // 创建索引
const index = new FlexSearch({
encode: 'icase',
tokenize: 'full',
threshold: 0,
resolution: 3,
depth: 3,
suggest: true
});
// 将数据添加到索引中
data.forEach((item, index) => {
index.add(index, item[0]);
});
// 处理搜索逻辑
function search() {
const query = document.getElementById('search-input').value.trim();
const result = index.search(query);
const output = document.getElementById('search-output');
if (result.length === 0) {
output.innerHTML = '没有找到符合条件的结果';
} else {
output.innerHTML = result.map((index) => {
const item = data[index];
return `
<div>
<h2>${item[0]}</h2>
<p>${item[3]}</p>
<a href='${item[2]}'>${item[1]}</a>
</div>
`;
}).join('');
}
}
</script>
</code></pre>
</head>
<body>
<input type='text' id='search-input' placeholder='请输入搜索关键词'>
<button onclick='search()'>搜索</button>
<div id='search-output'></div>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/ncG2 著作权归作者所有。请勿转载和采集!