function listSuggests(value) {
if (!value) return [];
const re = new RegExp(
value
.replace(/([\\\/\(\)\+\*\?\:\\[\]\^\$])/g, '\\$1')
.replace(/(\\.)/g, '$1.*?')
);
const items = window.items;
const result = items.filter((i) => re.test(i));
return result;
}
function onInput(evt) {
const suggests = listSuggests(evt.currentTarget.value.trim());
const s = document.getElementsByClassName('js-suggest')[0];
const ul = s.children[0];
ul.innerHTML = '';
if (!suggests.length) {
s.classList.add('hide');
} else {
s.classList.remove('hide');
ul.innerHTML = suggests.map((i) => `<li>${i}</li>`).join('');
}
}
function suggest(items) {
window.items = items;
const el = document.getElementsByClassName('js-input')[0];
el.addEventListener('input', onInput);
onInput({ currentTarget: el });
}
// 初始化 suggest 函数
suggest(['不匹配数据', '根据输入框的值', '从给定字符串数组中筛选出匹配的数据,依次显示在li节点中', '如果没有匹配的数据,请移除所有li节点,并隐藏.js-suggest节点']);