无法读取未定义的属性“包含”

时间:2020-09-16 14:55:08

标签: javascript

我一直收到此错误,而且我不知道为什么总是向这些元素分配undefined

function filterToDo(e) {
    const todos = toDoList.childNodes;
    
    todos.forEach(function(todo) {
        switch (e.target.value) {
            case "all":
                todo.style.display = 'flex';
                break;
            case "completed":
                if(todo.classList.contains("completed")){
                    todo.style.display = 'flex';
                } else {
                    todo.style.display = 'none';
                } 
            case "uncompleted":
                if(!todo.classList.contains("completed")){
                    todo.style.display = 'flex';
                } else {
                    todo.style.display = 'none';
                } 

        }
    });
}

2 个答案:

答案 0 :(得分:0)

就像评论中所说的那样,您不能调用未定义的内容,解决方案是在调用classList之前先检查是否存在classList。

这是一个可选更改的解决方案 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

function filterToDo(e) {
    const todos = toDoList.childNodes;
    
    todos.forEach(function(todo) {
        switch (e.target.value) {
            case "all":
                todo.style.display = 'flex';
                break;
            case "completed":
                if(todo.classList?.contains("completed")){
                    todo.style.display = 'flex';
                } else {
                    todo.style.display = 'none';
                } 
            case "uncompleted":
                if(!todo.classList?.contains("completed")){
                    todo.style.display = 'flex';
                } else {
                    todo.style.display = 'none';
                } 
         }
    });
}

答案 1 :(得分:0)

尝试过滤掉不是html元素的文本节点,因此它们没有classList属性:

function filterToDo(e) {
    const todos = [...toDoList.childNodes].filter(node => node instanceof HTMLElement);
    
    todos.forEach(function(todo) {
    //…
    });
}

function filterToDo(e) {
    const todos = Array.from(toDoList.childNodes).filter(node => node instanceof HTMLElement);
    
    todos.forEach(function(todo) {
    //…
    });
}
相关问题