***HTML***
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ToDos</title>
</head>
<body>
<h1>Todos....</h1>
<script src='todo-app.js'></script>
</body>
</html>
****JS***
const todos =[
{
text: 'Order Cat food',
completed: false
},
{
text: 'Clean Kitchen',
completed: true
},
{
text: 'Buy food',
completed: true
},
{
text: 'Do work',
completed: false
},
{
text: 'excercise',
completed: false
}
]
//任务 //你有3个待办事项[p元素] //为上面的每个待办事项添加一个p(使用对象的文本值作为段落的可见文本)
*** what I have so far*****
document.createElement('p')
let pt = todos.forEach(function (t){
if(t.completed == true){
let pt = t
}
})
console.log(pt)
下午好,
我正在尝试做这个挑战并陷入困境。我正在尝试完成已完成的待办事项并在HTML上显示待办事项的文本,然后显示未完成的待办事项(错误)并将这些待办事项显示为需要在html中完成的待办事项。< / p>
我能够过滤出真实的待办事项和控制台记录它们。但我无法退出该功能并使用它们来显示它。
当我尝试调用pt时,它表示未定义。我不明白它什么时候有它的代码。我猜我必须使用'this'关键字,我仍然在学习,并且还没有完全理解如何在保密的情况下实现它。
我的问题是如何使用'pt'varible输出完成到html中的待办事项然后再生成另一个变量来输出未完成的待办事项。我知道这样做,虚假的待办事项基本上是真正的待办事项,例如
todos.forEach(function(f){
if(f.completed == false){
console.log(f)
*** this should return all the todo's that have the property boolean of false if i'm not mistaken.
}}
P.S。对困惑感到抱歉。感谢任何意见。
答案 0 :(得分:1)
你可以把它分成更小的部分,(处理附加完整的待办事项,并附加它们),但你可以做这样的事情:
const todos = [{
text: 'Order Cat food',
completed: false
},
{
text: 'Clean Kitchen',
completed: true
},
{
text: 'Buy food',
completed: true
},
{
text: 'Do work',
completed: false
},
{
text: 'excercise',
completed: false
}
]
// get element you want to append to
var completedSection = document.getElementById('completed');
function handleTodos(array, location) {
var newArray = [];
// loop through array
array.forEach(function(item) {
// check if item.completed exists
if (item.completed) {
// if it does, append the item to the UL that was added to html
location.append(document.createElement("LI").innerHTML = item.text + ', ')
} else {
// if completed doesn't exist, push that to new array
newArray.push(item);
}
});
// return new array with incomplete tasks
return newArray;
}
var incompleteTasks = handleTodos(todos, completedSection);
console.log(incompleteTasks)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ToDos</title>
</head>
<body>
<h1>Todos....</h1>
<!-- added to place completed tasks under, this could be created with js too. -->
<ul id="completed"></ul>
<script src='todo-app.js'></script>
</body>
</html>
希望这有助于回答您的问题!