首页 > 解决方案 > 如何使用按钮创建和填充列表项?

问题描述

我正在尝试使用输入到文本字段中的数据创建要显示的项目列表。我的麻烦是,当我想添加第二个列表项时,第一个只会更新。我尝试了一些不同的东西,但我被卡住了。

function addToList() {
  let food = document.getElementById("food").value;
  let amount = document.getElementById("amount").value;
  let unit = document.getElementById("unit").value;

  document.getElementById("foodlist").innerHTML =
    (food + ' ' + amount + ' ' + unit + '.')

};
<input type="text" name="" value="food" id="food"><br>
<input type="text" name="" value="amount" id="amount"><br>

<select id="unit">
  <option value="oz">ounces</option>
  <option value="lb">pounds</option>
  <option value="servings">servings</option>
</select><br>

<button onclick="addToList()" type="button" name="button" id="addButton">add</button><br>

<li id="foodlist"></li>

我希望文本字段中的数据创建一个新的列表项,并在每次按下按钮时将数据添加到对象中。到目前为止,我所得到的只是列表项不断更新。

标签: javascripthtmlbuttonlistitem

解决方案


您需要创建一个ul元素并动态创建li元素,然后将它们附加为 this 的子级ul。请参见下面的代码:

function addToList() {
  let food = document.getElementById("food").value;
  let amount = document.getElementById("amount").value;
  let unit = document.getElementById("unit").value;

  let li = document.createElement("li");
  li.textContent = food + ' ' + amount + ' ' + unit + '.';
  document.getElementById("foodlist").appendChild(li);
}
<input type="text" name="" value="food" id="food">
<br>
<input type="text" name="" value="amount" id="amount">
<br>

<select id="unit">
  <option value="oz">ounces</option>
  <option value="lb">pounds</option>
  <option value="servings">servings</option>
</select>

<br>
<button onclick="addToList()" type="button" name="button" id="addButton">add</button>
<br>
<ul id="foodlist"></ul>


推荐阅读