您可以将以下代码集成到jquery中吗?每次我单击select,它都会添加很多下拉列表。当我单击select一次时,我希望它打开,如果我再次单击它,我希望下拉列表被删除。你能做到这一点吗?
提前感谢。
document.querySelectorAll('.custom-select').forEach(setupSelector);
function setupSelector(selector) {
selector.addEventListener('mousedown', e => {
if(window.innerWidth >= 420) {// override look for non mobile
e.preventDefault();
const select = selector.children[0];
const dropDown = document.createElement('ul');
dropDown.className = "selector-options";
[...select.children].forEach(option => {
const dropDownOption = document.createElement('li');
dropDownOption.textContent = option.textContent;
dropDownOption.addEventListener('mousedown', (e) => {
e.stopPropagation();
select.value = option.value;
selector.value = option.value;
select.dispatchEvent(new Event('change'));
selector.dispatchEvent(new Event('change'));
dropDown.remove();
});
dropDown.appendChild(dropDownOption);
});
selector.appendChild(dropDown);
// handle click out
document.addEventListener('click', (e) => {
if(!selector.contains(e.target)) {
dropDown.remove();
}
});
}
});
}