如果选择了选择标记中的选项,如何创建元素 [英] How do I create an element if the option in select tag is selected

查看:23
本文介绍了如果选择了选择标记中的选项,如何创建元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const ddselect = () => {
  let displayText = selectTag.options.text;
  let list = document.querySelector(".list");
  let listItem = document.createElement("li");
  listItem.innerHTML = displayText;
  console.log(listItem);
};

如果选择了选择标签中的选项,如何创建安莉? 我在SELECT标签中有8个选项。 我假设我必须遍历选项

推荐答案

虽然我不清楚您是要只在某个选定选项上创建li元素,还是要为每个选定选项创建不同的li元素,但我认为您要做的一种方法是...

<select>添加一个侦听change事件的事件侦听器,然后在此侦听器的回调函数内根据所选值/选项执行您想要的任何操作。

一个简短的例子;

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
var myOl = document.querySelector("#myol");
var select = document.querySelector("#myselect");

select.addEventListener("change", function(event){

  // Create a new Li element
  let newLi = document.createElement("li");
  // Set the Li Element's Text Content to the selected Option's Text Content
  newLi.textContent = event.target.options[event.target.selectedIndex].textContent;

  // Alternatively you could create a switch / if structure based on event.target.value
  /*
  switch( event.target.value )
  {
      case "1":
          // Do stuff in case of the first option
          break;
      case "2":
          // Do stuff in case of the second option
          break;
      // Etc
  }
  */

  // Add the new Li to the OL
  myOl.appendChild( newLi );

});
<select id="myselect">
  <option value="1">First Option!</option>
  <option value="2">Second Option!</option>
  <option value="3">Third Option!</option>
  <option value="4">Fourth Option!</option>
</select>

<ol id="myol"></ol>

这篇关于如果选择了选择标记中的选项,如何创建元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆