首页 > 解决方案 > 选择构建文本列表 HTML 的项目

问题描述

我正在尝试找出一种方法,以便您可以创建比萨店(或任何餐厅)的在线订购流程,这只是我选择的示例。这个想法是,当单击选项选项时,选定的项目将填充一个文本值,将可用选项中的所有选项添加到预先存在的列表中。例如,如果我想要一个“Viennese”和一个“Norcia e Funghi”,我会首先选择 Viennese(它会在文本中),然后选择 Norcia e Funghi,然后将其添加到文本列表中。

这是我想出的最好的方法(当然是在互联网的帮助下),我正在努力在大流行期间提高自己的技能,非常感谢您的帮助!我被困住了!

<html> 
<head>  
<script type="text/javascript">
function myNewFunction(element) {
    var text = element.options[element.selectedIndex].text;
    document.getElementById("test").innerHTML = text;
}

</script> 
</head>
<body>
<select id="box1" onChange="myNewFunction(this);">
<option value="1">Nessuna</option>
<option value="2">Viennese</option>
<option value="3">Norcia e Funghi</option>
</select>
<div id="test"></div


</body>

</html>

标签: javascripthtml

解决方案


如果我理解正确,您希望在<div id="test"></div>每次从列表中选择项目时更新而不是替换的内容。

<html> 
<head>  
<script type="text/javascript">
function myNewFunction(element) {
    var text = element.options[element.selectedIndex].text;
    //Check the items already outputted for the exact text
    //Use ... operator to convert into array
    var textItems = [...document.getElementById("test").children];
    
    //Filter through the elements to find one that includes matching text
    existingItem = textItems.filter(element => element.innerHTML.includes(text));
    
    // If there is an item with the text, then split the text by our seperator and add 1 to it before setting the inner text once more
    if (existingItem.length) {
      var itemAndQuantity = existingItem[0].innerText.split("-");
      var newQuantity = 1 + parseInt(itemAndQuantity[1]);
      existingItem[0].innerHTML = itemAndQuantity[0] + " - " + newQuantity;
    } else {
      //Create a new paragraph element, this could be a <li> instead
      var paragraph = document.createElement("p");
      //Add a - 1 for the quantity
      paragraph.innerHTML = text + " - 1";
      document.getElementById("test").appendChild(paragraph);
    }
}

</script> 
</head>
<body>
<select id="box1" onChange="myNewFunction(this);">
<option value="1">Nessuna</option>
<option value="2">Viennese</option>
<option value="3">Norcia e Funghi</option>
</select>
<div id="test"></div>


</body>

</html>

每次从下拉列表中选择一个项目时,这将向您的 div 添加一个新的段落元素。


推荐阅读