javascript - 如何使用按钮创建和填充列表项?
问题描述
我正在尝试使用输入到文本字段中的数据创建要显示的项目列表。我的麻烦是,当我想添加第二个列表项时,第一个只会更新。我尝试了一些不同的东西,但我被卡住了。
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>
我希望文本字段中的数据创建一个新的列表项,并在每次按下按钮时将数据添加到对象中。到目前为止,我所得到的只是列表项不断更新。
解决方案
您需要创建一个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>
推荐阅读
- python - 如何在出现字符时将列表的元素拆分为不同的子列表
- node.js - Firestore 云功能 - 如何返回第二个查询
- azure - 无法在 Azure 上启动 mariadb 容器,因为 mysql 用户似乎无权访问该卷
- arrays - BigQuery 使用记录字段更新常规字段
- r - 如何处理重复并偏爱一个版本,但并非总是如此
- firebase - 错误:没有创建 Firebase 应用“[默认]” - 调用 firebase.initializeapp() - 反应原生 Android
- android - 为什么片段和视图不会混淆?
- python - 在正则表达式中转义正斜杠没有什么效果?
- php - Laravel 雄辩的外表平均分
- c# - 对象类型未实现 IComparable