有一个实时搜索代码(我没有写),它运行良好,但最近出现错误,我不明白如何解决它以及可以做什么? 代码:
export async function liveSearch() {
const searchForms = document.querySelectorAll('.search-form');
searchForms.forEach(searchForm => {
const searchAll = searchForm.querySelectorAll('.search-form__input');
const results = searchForm.querySelector('.search-form__result');
let searchTerm = "";
async function showList(searchTerm) {
let searchJSON = await umi_macro('search', 'smart_search', [searchTerm], null, false);
searchJSON = Object.values(searchJSON)
if (searchJSON == ['search', 'smart_search']) {
searchJSON = []
}
results.innerHTML = "";
searchJSON
.filter((item) => {
return (
item.name.toLowerCase().includes(searchTerm) ||
item.link.toLowerCase().includes(searchTerm) ||
item.type.toLowerCase().includes(searchTerm)
);
})
.forEach((e) => {
const li = document.createElement("li");
const name = e.name
let str = insertMark(name, name.indexOf(searchTerm), [...searchTerm].length)
li.innerHTML = `
<a class="search-form__link ${e.type === 'category' ? 'red' : ''}" href="${e.link}" title="${name}">${str}</a>`;
results.appendChild(li);
});
console.log(results)
results.classList.add("active");
};
const inputCheckHandler = debounce(showList, 1500);
for (let search of [...searchAll]) {
search.addEventListener('keyup', () => {
if (typeof search.value === 'string'){
searchTerm = search.value.toLowerCase().trim();
inputCheckHandler(searchTerm);
}
});
}
function insertMark(searchString, searchPosition, searchLength) {
let result;
if (searchPosition === -1) {
result =
`<mark>${searchString.slice(0, searchPosition + searchLength + 1)}</mark>${searchString.slice(searchLength)}`
} else {
result =
`${searchString.slice(0, searchPosition)}<mark>${searchString.slice(searchPosition, searchPosition + searchLength)}</mark>${searchString.slice(searchPosition + searchLength)}`
}
return result;
}
document.addEventListener('click', closeSearch)
function closeSearch(e) {
let target = e.target;
if (!target.closest('.header__search-form') && results) {
results.classList.remove("active");
}
}
})
}
和一个错误: https://gyazo.com/8753a3ab0495d827f97eef07c5b010e3
当你点击它时,控制台显示: https://gyazo.com/220194ae821ca67322ef8ac5582780dc
我写了 toString() 方法,试图把它转换成一个字符串,它没有帮助,之前控制台在骂 toLowerCase() 请帮我解决这个问题,谢谢。