更新:尽管我还没有弄清楚这一点,但我找到了一个可行的替代方案:用Lunr.js|Jekyll Codex 搜索
我一直在使用lunr.js学习CloudCannon Academy关于Jekyll搜索的教程,但经过多次尝试和错误,我仍然没有让它发挥作用。
当我打开默认的web浏览器Microsoft Edge时,我在search.js
:中出现以下错误
search.js:47
Uncaught TypeError: idx.add is not a function
at search.js:47:11
at search.js:57:3
我一直在按部就班地学习教程,所以我基本上从上面链接的网页上复制了所有内容。我不明白的是,我确实像教程中那样定义了idx。通过检查源代码,我成功地检索了所有的post数据,并将它们存储在JSON中。我做错了什么?
为了您的信息,我在下面附上了我的代码:
(function() {
function displaySearchResults(results, store) {
var searchResults = document.getElementById('search-results');
if (results.length) { // Are there any results?
var appendString = '';
for (var i = 0; i < results.length; i++) { // Iterate over the results
var item = store[results[i].ref];
appendString += '<li><a href="' + item.url + '"><h3>' + item.title + '</h3></a>';
appendString += '<p>' + item.content.substring(0, 150) + '...</p></li>';
}
searchResults.innerHTML = appendString;
} else {
searchResults.innerHTML = '<li>No results found</li>';
}
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] === variable) {
return decodeURIComponent(pair[1].replace(/+/g, '%20'));
}
}
}
var searchTerm = getQueryVariable('query');
if (searchTerm) {
document.getElementById('search-box').setAttribute("value", searchTerm);
// Initalize lunr with the fields it will be searching on. I've given title
// a boost of 10 to indicate matches on this field are more important.
var idx = lunr(function () {
this.field('id');
this.field('title', { boost: 10 });
this.field('content');
});
for (var key in window.store) { // Add the data to lunr
idx.add({
'id': key,
'title': window.store[key].title,
'content': window.store[key].content
});
var results = idx.search(searchTerm); // Get lunr to perform a search
displaySearchResults(results, window.store); // We'll write this in the next section
}
}
})();
我遇到了同样的问题,并在这个Stackoverflow答案中找到了帮助。
问题是,有些教程是为Lunr 1.x编写的,这是添加索引的正确方法。
在Lunr2.x中,需要在定义字段的同一函数中添加内容。
我与Lunr 2.3.0和Jekyll的工作代码:
var idx = lunr(function() {
this.ref('id');
this.field('title', { boost: 10 });
this.field('content', { boost: 5 });
this.field('author');
this.field('categories');
{% assign count = 0 %}
{% for post in site.posts %}
this.add({
title: {{post.title | jsonify}},
content: {{post.content | strip_html | jsonify}},
category: {{post.category | jsonify}},
tags: {{post.tags | jsonify}},
id: {{count}}
});
{% assign count = count | plus: 1 %}
{% endfor %}
});