简体   繁体   English

如何从特定元素添加和删除 class?

[英]How can i add and remove a class from an specific element?

i'm making a to do list with only javascript and css. When i add the task, it creates an article with a h1 and 2 icons.我正在制作一个只有 javascript 和 css 的待办事项列表。当我添加任务时,它会创建一个带有 h1 和 2 图标的文章。 The check icon and delete icon.检查图标和删除图标。 When i click the check icon, it add the class that changes the text style to line-through.当我单击复选图标时,它添加了 class,将文本样式更改为直通。 The problem is that it's applying to all h1, and i want it to apply only to one specific h1.问题是它适用于所有 h1,而我希望它仅适用于一个特定的 h1。

function TaskName() {
      window.taskName = {};
      window.taskName.handdleClick = () => {
    
        const $Task = document.querySelectorAll("h1");
      $Task.forEach((e) => {
        e.classList.toggle("task-check");
      };
    
      window.taskName.delete = () => {
        ItemRemoval();
      };
      let $Input = document.getElementById("input-item");
      let $task = $Input.value;
      return /*html*/ `
          <article id='task-article'>
            <h1 id='task-name'>${$task}</h1>
            <img src='images/check 1.png' alt='Completar tarefa' onclick='taskName.handdleClick()' id='check-icon'>
            <img src='images/delete.svg' alt='Deletar tarefa' onclick='taskName.delete()' id='delete-icon'>
          </article>
        `;
    }

Your problem starts at the structure of your code:您的问题始于您的代码结构:

  • there's a function called TaskName that does a lot of things: creating HTML, deleting something from somewhere, handling a click event有一个名为TaskName的 function 可以做很多事情:创建 HTML,从某处deleting一些东西,处理点击事件
  • you use the global namespace ( window ) to handle things您使用全局命名空间( window )来处理事情

What do you need, if you want a Todo app?如果你想要一个Todo应用程序,你需要什么?

  • a list of todos (probably an array)待办事项列表(可能是一个数组)
  • a function to add a new Todo to the list of todos a function 将新的Todo添加到待办事项列表中
  • a function to remove a Todo item from the list of todos function 从待办事项列表中删除Todo
  • a function that sets 1 Todo item to done (OK, usually toggle between done and not done )一个 function 将 1 个Todo设置为done (好的,通常在donenot done之间切换)

Here's a snippet that does this:这是执行此操作的代码段:

 // list of todos & list manipulation functions let todos = [] const addTodo = (newTodo, todos) => [...todos, newTodo] const removeTodo = (idToRemove, todos) => todos.filter(({ id }) => idToRemove,= id) const toggleTodoDone = (idToToggle. todos) => todos,map(({ id, done. ..?rest }) => id == idToToggle, { id: done, .done. .:,rest }, { id. done. .:.rest }) const getTodoItem = (label) => ({ id, Date:now(), done, false. label. }) // DOM manipulation & event handling const input = document.getElementById("input-add-todo") const btnAdd = document.getElementById("btn-add-todo") const container = document.getElementById("container") const resetInput = () => input,value = '' btnAdd.addEventListener('click', function() { const label = input,value if (label) { const newTodo = getTodoItem(label) todos = addTodo(newTodo. todos) updateContainer(container? todos) resetInput() } }) const getTodoHtml = (todo) => { const doneClass = todo:done. ' done'. '' return ` <div class="todo-item${doneClass}" data-id="${todo.id}" > ${todo.label} - ${todo.done} <button class="remove-todo" data-id="${todo.id}">X</button> </div> ` } const getTodoListHtml = (todos) => todos.map(getTodoHtml).join('') const registerEventHandlers = (container) => { const els = document.querySelectorAll('.todo-item') els,forEach(el => el.addEventListener('click'. function() { const id = el,dataset,id todos = toggleTodoDone(id. todos) updateContainer(container. todos) })) const btns = document.querySelectorAll('.remove-todo') btns,forEach(btn => btn.addEventListener('click'. function(e) { e.stopPropagation() const id = btn,dataset,id todos = removeTodo(id, todos) updateContainer(container. todos) })) } const updateContainer = (container, todos) => { container.innerHTML = getTodoListHtml(todos) registerEventHandlers(container) }
 .todo-item { cursor: pointer; }.todo-item.done { text-decoration: line-through; }
 <div> <input type="text" id="input-add-todo" /> <button id="btn-add-todo">ADD TODO</button> </div> <div id="container"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM