html 从待办事项列表中删除

ocebsuys  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(104)

我正在做一个待办事项列表的网页,我被困在如何从列表中删除一个待办事项名称,而不删除整个事情。

const todoList = [];

function addTodo() {
    const inputElement = document.querySelector('.js-input');
    const todoName = inputElement.value;

    if (todoName.trim() !== '') {
        todoList.push(todoName);
        const todoListElement = document.querySelector('.js-todo-list');
        todoListElement.innerHTML += `
        <li class="js-todo-items">
        ${todoList.length}. ${todoName}
        </li>
        <button class="final-button" id="button" onclick="todoFinished()">✅</button>
        <button class="final-button" id="button" onclick="todoFinished()">🚫</button><br>`;
        inputElement.value = '';
    }
}

function clearTodo() {
    todoList.length = 0;
    const todoListElement = document.querySelector('.js-todo-list');
    todoListElement.innerHTML = '';
}

function todoFinished(){
    todoList.pend(todoName)
}

我试图使名称具有不同的属性,这样我就可以删除选定的一个,但我不知道如何做到这一点。

w1e3prcc

w1e3prcc1#

你在html中显示元素时遇到了问题。显示逻辑不应该在添加逻辑。下面是重写的代码

const todoList = [];
const todoListElement = document.querySelector('.js-todo-list');

function addTodo() {
    const inputElement = document.querySelector('.js-input');
    const todoName = inputElement.value;

    if (todoName.trim() !== '') {
        todoList.push(todoName);
        displayTodoList();
        inputElement.value = '';
    }
}

function removeTodo(index) {
    todoList.splice(index - 1, 1);
    displayTodoList();
}

function displayTodoList() {
    todoListElement.innerHTML = '';

    todoList.forEach((todoName, index) => {
        const listItem = document.createElement('li');
        listItem.className = 'js-todo-items';
        listItem.textContent = `${index + 1}. ${todoName}`;

        const completeButton = createButton('✅', () => todoFinished(index + 1));
        const removeButton = createButton('🚫', () => removeTodo(index + 1));

        todoListElement.appendChild(listItem);
        todoListElement.appendChild(completeButton);
        todoListElement.appendChild(removeButton);
        todoListElement.appendChild(document.createElement('br'));
    });
}

function createButton(text, onClick) {
    const button = document.createElement('button');
    button.className = 'final-button';
    button.textContent = text;
    button.onclick = onClick;
    return button;
}

function todoFinished(index) {
    // Implement your logic for marking a todo as finished (if needed)
    console.log(`Todo at index ${index} is marked as finished.`);
}

// Initial display
displayTodoList();

相关问题