我需要处理一个事件并获取其parentNode。但是,我得到一个错误:'TodoList'类型上不存在'Property'parentNode'
我尝试使用this.parentNode,但仍然出现错误
class TodoList {
constructor() {
const checkbox: HTMLElement =
todoItem.querySelector('.checkbox');
checkbox.addEventListener('change', this.toggleTodoItem);
}
toggleTodoItem(): void {
let node = this.parentNode;
node.classList.toggle('completed');
};
}
答案 0 :(得分:0)
您的TodoList
类根本不包含名为parentNode
的实例属性,这就是为什么会出现错误的原因。相反,您是否要编写类似this的代码?
// todoItem is accessible from somewhere in your code
declare const todoItem: HTMLElement
class TodoList {
private checkboxNode: HTMLElement
constructor() {
const maybeCheckboxNode = todoItem.querySelector<HTMLElement>('.checkbox');
if (maybeCheckboxNode) {
this.checkboxNode = maybeCheckboxNode
this.checkboxNode.addEventListener('change', this.toggleTodoItem);
} else throw new Error("Element not found.")
}
toggleTodoItem(): void {
// assuming you mean the parent of checkbox node by `this.parentNode` in sample
// cast node here, because parentNode doesn't have narrowed type
let node = this.checkboxNode.parentNode as HTMLElement | null;
node && node.classList.toggle('completed');
};
}