1

有人可以解释为什么 clearTimeout 函数在下面不起作用吗?每当我调用它时,仍然会调用 setTimeout 函数......谢谢!

let todo = document.getElementById('todo');
let todoList = document.getElementById('todo_list');
let timer;

form.addEventListener('submit', newtodo);

function newtodo() {
    let todoItem = document.createElement('li');
    let timesItem = document.createElement('i');

    timesItem.classList.add('fa', 'fa-times-circle');

    todoItem.innerHTML = todo.value;

    todoList.appendChild(todoItem).prepend(timesItem);

    timesItem.addEventListener('click', function() {
        todoItem.style.textDecoration = "line-through";
        todoItem.style.color = "grey";

        timer = setTimeout(removeTodoItem, 3000);;    
        
        timesItem.addEventListener('click', function() {
            todoItem.style.textDecoration = "none";
            todoItem.style.color = "black";
            clearTimeout(timer);            
        });
    });   

    todo.value = '';

    function removeTodoItem() {
        todoList.removeChild(todoItem);
    }    
}
4

2 回答 2

0

这是我为任何感兴趣的人提出的解决方案:

let todo = document.getElementById('todo');
let todoList = document.getElementById('todo_list');
let timer;

form.addEventListener('submit', newtodo);

function newtodo() {
    let todoItem = document.createElement('li');
    let timesItem = document.createElement('i');

    timesItem.classList.add('fa', 'fa-times-circle');

    todoItem.innerHTML = todo.value;

    todoList.appendChild(todoItem).prepend(timesItem);

    let idx = 0;

    timesItem.addEventListener('click', function() {

        if(idx == 0) {
            todoItem.style.textDecoration = "line-through";
            todoItem.style.color = "grey";
            timer = setTimeout(removeTodoItem, 3000);;  
            idx++;  
        } else {
            todoItem.style.textDecoration = "none";
            todoItem.style.color = "black";
            clearTimeout(timer);
            idx--;
        }         
    });

    todo.value = '';

    function removeTodoItem() {
        todoList.removeChild(todoItem);
    }    
}
于 2021-02-08T20:44:59.010 回答
-1

这是在这种情况下发生的情况:

newTodo函数将在表单提交后运行。

并通过运行newTodo您为按钮定义 onClick 事件侦听器和将在 3 秒内触发的超时函数。

如果您在 3 秒前单击timesItem,它将清除超时并且不会运行。

如果你还有什么问题可以问我。

于 2021-02-07T19:12:24.113 回答