首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从选中框中选择后重置html内容

从选中框中选择后重置html内容
EN

Stack Overflow用户
提问于 2022-03-06 22:10:19
回答 1查看 154关注 0票数 -1

我用innerHTML投影选定的值,我想在每个选定的值之后重置innerHTML

代码语言:javascript
运行
复制
 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 = "";
    }
代码语言:javascript
运行
复制
<select class="select" onchange="dropdown(event)">
      <option>choose</option>
      <option value="op1">Option 1</option>
      <option value="op2">Option 2</option>
    </select>

EN

回答 1

Stack Overflow用户

发布于 2022-03-06 22:58:25

您可以将元素保存到变量中,然后在函数再次调用时删除它。(oldDiv在下面的示例实现中。)

代码语言:javascript
运行
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71374598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档