我用innerHTML投影选定的值,我想在每个选定的值之后重置innerHTML
const body = document.body;
function dropdown(e) {
const select2 = document.querySelector(".select");
let selected = select2.options[select2.selectedIndex].value;
const div = document.createElement("div");
div.innerHTML = `<div>${selected}</div>`;
body.appendChild(div);
select2.options[select2.selectedIndex].value = "";
}
<select class="select" onchange="dropdown(event)">
<option>choose</option>
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
</select>
发布于 2022-03-06 22:58:25
您可以将元素保存到变量中,然后在函数再次调用时删除它。(oldDiv
在下面的示例实现中。)
<select class="select">
<option value="">choose</option>
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
</select>
<script>
let oldDiv = null // the newest created div will be stored here
document.querySelector(".select").addEventListener("change", function(event) { // this way of adding an event listener is preferable, as it allows you to add multiple listeners to the same element
if(oldDiv) oldDiv.remove() // remove the old div (if it exists)
const div = document.createElement("div") // create new div
div.textContent = event.target.value // set text content of new div to the selected value of the dropdown menu
document.body.append(div) // add new div to body
oldDiv = div // save new div in variable oldDiv, so it gets removed on next function call
})
</script>
https://stackoverflow.com/questions/71374598
复制相似问题