使用 flexsearch 写一个搜索模板 数据在 searchjson 文件里 searchjson内容为没有农药化肥这颗羊奶果无疑是最自然的果实2023年03月03日article20230318html2023年02月16日我发现三年前所种植的羊奶果树开始结果了这是三年来的第一次丰收。身为一名农夫能够看到自己种植的作物顺利成长获得丰收是非常开心的一件事情。 三岁的玥玥与年长孩子玩耍中的困难与
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>搜索模板</title>
<script src="https://unpkg.com/flexsearch/dist/flexsearch.min.js"></script>
<script>
// 从 search.json 文件中读取数据并建立索引
fetch('search.json')
.then(response => response.json())
.then(data => {
const index = new FlexSearch.Document({
doc: {
id: 2,
field: [0, 1, 2, 3]
},
cache: true
});
<pre><code> index.add(data);
// 监听搜索框的输入事件
const searchInput = document.getElementById('search-input');
searchInput.addEventListener('input', () => {
const query = searchInput.value;
const result = index.search(query, {limit: 10});
// 渲染搜索结果
const searchResult = document.getElementById('search-result');
searchResult.innerHTML = '';
result.forEach(item => {
const title = item[0];
const date = item[1];
const url = item[2];
const li = document.createElement('li');
const a = document.createElement('a');
const p = document.createElement('p');
a.href = url;
a.innerText = title;
p.innerText = date;
li.appendChild(a);
li.appendChild(p);
searchResult.appendChild(li);
});
});
});
</script>
</code></pre>
</head>
<body>
<h1>搜索模板</h1>
<input type="text" id="search-input" placeholder="请输入搜索内容">
<ul id="search-result"></ul>
</body>
</html>
原文地址: http://www.cveoy.top/t/topic/bJO8 著作权归作者所有。请勿转载和采集!