如何将项目添加到 javascript 数组并在 html <li> 中显示该数组
How do I add items to a javascript array and display the array in a html <li>
我错过了一些我知道的非常基本的东西,但我似乎找不到解决方案。
我很难理解html和Javascript元素如何交互。我的代码有一些正确的内容,但我知道它远非正确。我也不确定将javascript代码放在html文件本身中是否重要,或者我是否可以将其保存在外部js文件中并调用它。
无论如何,我正在尝试创建一个待办事项列表。我想:- 将项目存储在我的"列表"数组中- 显示有序列表中的全部项目- 允许用户向列表中添加新项目(通过索引页面上的文本输入)
任何指导将不胜感激
我的代码:
<body>
<div id="wrapper">
<h3></h3>
<ol id="unfinished">
<form name="addToList">
<li><input type="text" id="newItem"></li>
</form>
<li></li>
(在我的js文件中)
var list = []
var newItem = document.getElementsById("newItem");
你需要的是:
- 新待办事项的"输入"字段
- 列表,例如用于显示项目的"OL"列表
- 将新项添加到列表的按钮 侦听
- 按钮的事件侦听器
举个例子:
<ol id="listforitems">
<li>Item that is already there</li>
</ol>
<input type="text" id="newlistitem">
<input type="button" id="buttonfornewitem" value="Add to list">
这些已经是前几点了。 现在 JS 带来了魔力
// event listener that waits for "click" event on the button
document.getElementById('buttonfornewitem').addEventListener('click', function(e) {
// we create a new element to append it to the list
var newElement = document.createElement('li');
// we define the content of the new element to be the value that has been entered in the input-field
newElement.innerHTML = document.getElementById('newlistitem').value;
// then we add it to the list
document.getElementById('listforitems').appendChild(newElement);
// optional: reset the input field so that you can add another todo-task
document.getElementById('newlistitem').value = '';
});
如果您
的目标是实现一种将项目插入列表的简单方法,我认为@Zim84的解决方案非常适合您的需求。
但是,如果你想实现一个待办事项列表或类似的东西,我建议你看看TodoMVC,在那里可以找到关于这种工作的例子(将项目插入到具有双向绑定的列表中 - 即列表和输入数据之间同步的项目)在普通的Javascript和许多其他框架和库中。
相关文章:
- 如何在映射数组中添加换行符
- javascript结合了数组和字典
- 需要帮助设置json数组
- 从数组中删除 li 和
- 将内容从 JSON 数组附加到 li 元素
- 将文本发送到数组中的特定li
- 如何使用 JQuery 数组将类添加到 li
- 将数组对象转换为嵌套的 ul li 元素
- 如何获取所有LI UL元素ID值并将它们放置在JavaScript数组中
- JQuery:获取"数据值=n〃;在shuffle数组中可见的li
- 如何在jQuery中循环遍历数组,并将数组中的值附加到li中
- 使用JsonML将数组元素追加到li's
- 我需要把我的LI数组元素放到UL中,但我不能
- 从数组中填充li元素,如果选中:false(打开/关闭按钮),则删除重复项并添加值
- 根据字符串数组更改li元素的颜色
- jQuery从数组中设置元素li数据
- 从数组创建 li 数据角色=列表分隔符
- 在数组中动态存储li id
- 二叉树数组
- & lt; li>超文本标记语言
- jQuery Supersized:如何使用从LI创建的数组