简体   繁体   English

将所选项目附加到列表

[英]Append selected items to a list

I want to create a dropdown box with a few items.我想创建一个包含几个项目的下拉框。 Once the user selects the item and clicks the '+' button, the item is added below to a 'basket' section.一旦用户选择了该项目并单击“+”按钮,该项目就会添加到下方的“篮子”部分。 They should be able to add multiple items over and over.他们应该能够一遍又一遍地添加多个项目。

 document.getElementById("button").onclick = function() { var a = document.getElementById("selection"); var item = a.options[a.selectedIndex].text; document.getElementById("basket").innerHTML = item; var counter = 1; while (counter <= 1) { var list = document.write(item); counter++; } }
 <h1>Select your items!</h1> <form id="myForm"> <p>Item: <select id="selection"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> <option value="4">four</option> </select> <button id="button">+</button></p> </form> <br><br><br> <h1>Basket</h1> <p id="basket"></p>

When the button is pressed, all current content disappears and the item selected appears on its own.按下按钮时,所有当前内容都会消失,所选项目会单独出现。

The button in the form has no type="button" .表单中的按钮没有type="button" Therefore it is used as submit button and that's why you get the blank page.因此,它被用作提交按钮,这就是为什么你得到空白页。

You don't need a loop.你不需要循环。

Example例子

 var button = document.getElementById("button"); var select = document.getElementById("select"); var basket = document.getElementById("basket"); // Add text function addToBasket() { var li = document.createElement("li"); li.innerHTML = select.options[select.selectedIndex].text; basket.appendChild(li); } button.addEventListener("click", addToBasket);
 <h1>Select your items!</h1> <form id="myForm"> <p>Item: <select id="select"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> <option value="4">four</option> </select> <button id="button" type="button">+</button></p> </form> <h1>Basket</h1> <ul id="basket"></ul>

You are not concatenating them.你没有连接它们。 document.getElementById("basket").innerHTML = item; removes everything in the basket and add only the selected one.删除篮子中的所有内容并仅添加选定的内容。

Use this to concatenate the new item with what already exists in the basket document.getElementById("basket").innerHTML += item;使用它来将新项目与篮子document.getElementById("basket").innerHTML += item;已经存在的项目连接起来。getElementById document.getElementById("basket").innerHTML += item; . . You can style it to make the basket look nice.您可以设计它以使篮子看起来漂亮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM