我怎么能得到一个EventListener上的选择下拉框使用循环工作如预期



我有一些HTML选项卡使用单选按钮来控制它们。然而,我使用一个选择下拉菜单和一些javascript来控制它们在移动屏幕上的大小。

// Get select element for mobile navigation
const select = document.getElementById("location");
// Event listener for selecting tabs event for mobile
select.addEventListener("change", (e) => {
const target = e.target.value;
const venueTabs = document.querySelectorAll(".tabs__radio");
for (let i = 0; i < venueTabs.length; i++) {
if (venueTabs[i].id === target) {
venueTabs[i].setAttribute("checked", "checked");
console.log(venueTabs[i], target);
} else if (venueTabs[i].id !== target) {
venueTabs[i].removeAttribute("checked");
}
}
});

我的eventListener似乎可以工作,并且正在退出预期的内容。它将选项卡div idevent target进行比较。

但是这似乎只能当我测试每个选择选项两次,在第三次尝试选项卡内容消失(css开关display: none)。

我似乎无法找出是什么导致了错误。

我用代码代码建立了一个沙箱https://codesandbox.io/s/nice-ramanujan-2yq1r?file=/src/index.js帮助调试它。如果下拉菜单没有显示,你可能需要查看手机/低于700像素宽&它将显示选择下拉菜单。

有谁能帮忙找出导致这个bug的原因吗?我之前已经硬编码了工作完美的EventListener,它看起来像这样

select.addEventListener("change", (e) => {
const target = e.target;
const tabone = document.getElementById("tab0");
const tabtwo = document.getElementById("tab1");
const tabthree = document.getElementById("tab2");
const tabfour = document.getElementById("tab3");
if (target.value === "tab0") {
tabtwo.removeAttribute("checked");
tabthree.removeAttribute("checked");
tabfour.removeAttribute("checked");
tabone.setAttribute("checked", "checked");
} else if (target.value === "tab1") {
tabthree.removeAttribute("checked");
tabfour.removeAttribute("checked");
tabone.removeAttribute("checked");
tabtwo.setAttribute("checked", "checked");
} else if (target.value === "tab2") {
tabfour.removeAttribute("checked");
tabone.removeAttribute("checked");
tabtwo.removeAttribute("checked");
tabthree.setAttribute("checked", "checked");
} else if (target.value === "tab3") {
tabone.removeAttribute("checked");
tabtwo.removeAttribute("checked");
tabthree.removeAttribute("checked");
tabfour.setAttribute("checked", "checked");
}
});

但是,它不够动态,不能容纳任意数量的选项卡。

这并不需要在所有的单选按钮上进行任何循环-只需选择您想通过其id设置为选中的一个元素:

select.addEventListener("change", (e) => {
const target = e.target.value;
const venueTab = document.querySelector("#"+target);
venueTab.checked = true;
});

最新更新