问题描述
我试图弄清楚如何为我的下拉值添加名称,默认情况下该值为空。我想称其为“全部显示”。它与地图过滤器一起使用,因此可以按功能显示值。
function buildDropDownList(title,listItems) {
const filtersDiv = document.getElementById("filters");
const mainDiv = document.createElement("div2");
const filterTitle = document.createElement("h3");
filterTitle.innerText = title;
filterTitle.classList.add("py12","txt-bold");
mainDiv.appendChild(filterTitle);
const selectContainer = document.createElement("div2");
selectContainer.classList.add("select-container","center");
const dropDown = document.createElement("select");
dropDown.classList.add("select","filter-option");
const selectArrow = document.createElement("div2");
selectArrow.classList.add("select-arrow");
const firstOption = document.createElement("option");
dropDown.appendChild(firstOption);
selectContainer.appendChild(dropDown);
selectContainer.appendChild(selectArrow);
mainDiv.appendChild(selectContainer);
for (let i = 0; i < listItems.length; i++) {
const opt = listItems[i];
const el1 = document.createElement("option");
el1.textContent = opt;
el1.value = opt;
dropDown.appendChild(el1);
filtersDiv.appendChild(mainDiv);
}
解决方法
该项目是一个没有值的选项。最好的解决方案是避免获取空元素,但是如果不可能,则可以进行一些小的调整,例如:
for (let i = 0; i < listItems.length; i++) {
const opt = listItems[i];
const el1 = document.createElement("option");
el1.textContent = (opt && opt.trim()) ? opt : "Show all";
el1.value = opt;
dropDown.appendChild(el1);
}
此外,请确保正确关闭循环的花括号。