var view = {
displayTodos: function () {
var todosUl = document.querySelector('ul');
todosUl.innerHTML = '';
todoList.todos.forEach(function(todo){
var todoLi = document.createElement('li');
var todoTextWithCompletion = ''
if (todo.completed) {
todoTextWithCompletion = '(X) ' + todo.todoText;
}
else {
todoTextWithCompletion = '( ) ' + todo.todoText;
}
todoLi.textContent = todoTextWithCompletion;
todoLi.appendChild(this.createDeleteButton());
todosUl.appendChild(todoLi);
});
},
createDeleteButton: function () {
var deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.className = 'deleteButton';
return deleteButton;
}
};
我试图在列表中的每个项目中添加一个按钮,但现在每当我运行view.displayTodos()时,我都会收到错误消息:" TypeError:this.createDeleteButton不是函数"
我认为问题与线路有关: todoLi.appendChild(this.createDeleteButton()); 但我不知道为什么它不起作用。
提前感谢您的帮助
答案 0 :(得分:1)
将this.createDeleteButton()
替换为view.createDeleteButton()
似乎有效
谢谢胡安
答案 1 :(得分:-1)
最简单的解决方法是将this
保存到that
var view = {
displayTodos: function () {
console.log("displayTodos",this);
var arr=[1,2];
var that=this;
arr.forEach(function(todo){
// console.log("todolist",this);
that.createDeleteButton();
});
},
createDeleteButton: function () {
console.log("create");
}
};
view.displayTodos();

第二种方法::::将当前对象作为第二个参数传递
var view = {
displayTodos: function () {
var arr=[1,2];
arr.forEach(function(todo){
this.createDeleteButton();
},this);
},
createDeleteButton: function () {
console.log("create");
}
};
view.displayTodos();