2 回答
![?](http://img1.sycdn.imooc.com/545864190001966102200220-100-100.jpg)
TA贡献2080条经验 获得超4个赞
document.querySelector('#todo').appendChild(p);您正在附加到一个不存在的#todo元素。投入一个<div id="todo"></div>,它会工作。
在职的:
// The array
const todos = [{
text: 'wake up',
completed: true
}, {
text: 'get some food',
completed: true
}, {
text: 'play csgo',
completed: false
}, {
text: 'play minecraft',
completed: true
}, {
text: 'learn javascript',
completed: false
}];
//creating p elements and assigning their text content to each "text" property of the "todos" array
todos.forEach(function(todo){
let p = document.createElement('p');
p.textContent = todo.text;
document.querySelector('#todo').appendChild(p);
})
<body>
<h1>Todos</h1>
<form id="form">
Add a new todo
<input type="text" placeholder="Type your first name" name="firstName">
<button>Submit</button>
</form>
<div id="todo"></div>
<script src="todo-app.js"></script>
</body>
![?](http://img1.sycdn.imooc.com/545864000001644402200220-100-100.jpg)
TA贡献1831条经验 获得超4个赞
这里的主要问题是该#todos
元素不存在于您的 HTML 中,这意味着todos
您的页面中没有显示数据的“目的地” 。
作为对您的应用程序的改进,请考虑定义一个可重用的函数,例如updateView()
更新#todo
元素的内容以显示todos
数组中的当前数据。在您的应用程序中,可以称为:
提交表单后,显示新添加的待办事项
加载时,显示初始数据
实现这一点的一种方法如下:
// The array
const todos = [{
text: 'wake up',
completed: true
}, {
text: 'get some food',
completed: true
}, {
text: 'play csgo',
completed: false
}, {
text: 'play minecraft',
completed: true
}, {
text: 'learn javascript',
completed: false
}];
/* Reusable function that updates the view container with current
data in todos array */
function updateView() {
const container = document.getElementById("todo");
/* Clear list */
container.innerHTML = "";
/* Populate list with current todos data */
todos.forEach(function(todo) {
const p = document.createElement('p');
p.textContent = todo.text;
container.appendChild(p);
});
}
const form = document.getElementById("form");
/* Add form submit event handler to add actual todo to list(s) */
form.addEventListener("submit", function(event) {
/* Prevent default "page reload" form submit behavior */
event.preventDefault();
/* Extract text from input field */
const text = form.querySelector('input[name="firstName"]').value;
/* Add new todo item to todos array (model) */
todos.push({
text: text,
completed: false
});
/* Update container with added todo data */
updateView();
});
/* Populate container with inital data */
updateView();
<h1>Todos</h1>
<form id="form">
Add a new todo
<input type="text" placeholder="Type your first name" name="firstName">
<button>Submit</button>
</form>
<!-- Add a DOM element that contains the actual display list -->
<div id="todo">
</div>
添加回答
举报