我有一个系统,当输入特定值时,它会将选项添加到 Select 元素中.当该值更改时,它只会将更多选项附加到 Select 元素.如何删除旧选项?
示例代码:
const sections = ["Section 1", "Section 2"];
const sections2 = ["Section 3", "Section 4"];
const [selectedValue, setValue] = useState("");
if (selectedValue == "1") {
sections?.forEach((option) => {
const selectElement = document.getElementById(
"section"
) as HTMLSelectElement;
const optionElement = document.createElement("option");
optionElement.value = option.sectionName;
optionElement.text = option.sectionName;
selectElement?.add(optionElement);
});
} else {
sections2?.forEach((option) => {
const selectElement = document.getElementById(
"section"
) as HTMLSelectElement;
const optionElement = document.createElement("option");
optionElement.value = option.sectionName;
optionElement.text = option.sectionName;
selectElement?.add(optionElement);
});
}
return (
<form>
<select onChange={e => setValue(e)}>
<option>Section List 1</option>
<option>Section List 2</option>
</select>
<select id="section">
</select>
</form>
)