JavaScript关键词过滤功能实现
let userValue = document.querySelector('.content'); let KeywordFiltering = [ { name: '名字', class: 'username', data: ['嘻嘻', '哈哈', '嘿嘿'] }, { name: '文案', class: 'Copywriting', data: [4, 5, 6] }, { name: '全选', class: 'selectall', data: [7, 8, 9] } ];
const optionList = document.querySelector('.option'); const listDivs = document.querySelectorAll('.list div');
KeywordFiltering.forEach(item => { let li = document.createElement('li'); li.innerText = item.name; optionList.appendChild(li); let div = document.createElement('div'); div.className = item.class; document.querySelector('.list').appendChild(div);
li.onclick = () => { listDivs.forEach(allDiv => allDiv.style.display = 'none'); div.style.display = 'block'; optionList.style.display = 'none';
document.querySelector('.confirm').onclick = () => {
if (item.data.includes(userValue.value)) {
alert('已存在');
return;
}
let span = document.createElement('span');
span.innerText = userValue.value;
div.appendChild(span);
item.data.push(userValue.value);
span.onclick = () => {
span.remove();
item.data = item.data.filter(item => item !== span.innerText);
console.log(span, item.data);
};
console.log(item.data, userValue.value);
};
};
item.data.forEach(subitem => { let span = document.createElement('span'); span.innerText = subitem; div.appendChild(span); span.onclick = () => { span.remove(); item.data = item.data.filter(item => item !== subitem); console.log(span, item.data); }; }); });
document.querySelector('.choice').onmouseover = () => { optionList.style.display = 'block'; listDivs.forEach(allDiv => allDiv.style.display = 'none'); };
optionList.onmouseleave = () => { optionList.style.display = 'none'; };
原文地址: https://www.cveoy.top/t/topic/p3Zd 著作权归作者所有。请勿转载和采集!