簡體   English   中英

如果選擇了 select 標記中的選項,我如何創建元素

[英]How do I create an element if the option in select tag is selected

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

如果選擇了 select 標簽中的選項,如何創建 li? 我在 select 標簽中有 8 個選項。 我假設我必須遍歷選項

雖然我不清楚你是想只在某個選定的選項上創建一個 li 元素,還是為每個選定的選項創建不同的 li 元素,但我認為你正在嘗試做的一種方法是......

向您的<select>添加一個事件偵聽器來偵聽change事件,然后在此偵聽器的回調 function 中根據所選值/選項執行您想要的任何操作。

一個簡短的例子;

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM