如何将我的 class 任务定位为要处理的事件侦听器?

How do I target my class task for the event Listener to Handle?

我的编辑删除和保存按钮不起作用,那是因为事件侦听器正在传递一个没有任何内容的元素,但我想定位 class <div class="task" date-id = "${id}"> 事件侦听器。

这是错误的地方:

elements.list.addEventListener('click',event => elements.list 是错误的,因为它没有持有任何东西。但我想将 <div class="task" date-id = "${id}"> 定位为 eventEventListener。

请查看完整代码,以便您有更好的想法:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To-do App</title>
    <script src="js/main.js" defer></script>
    <script src="js/dateTime.js" defer></script>

    <link rel="stylesheet" href="css/main.css" />
</head>

<body>
<div class="header">
      <h1>To-Do List</h1>
  
      <div class="time">
        <div class="dateTime"></div>
        <div class="day"></div>
      </div>
    </div>
    <form id="new-task-form">
      <div class="add-task">
        <input type="text" name="new-task-input" id="new-task-input" placeholder="What do you have planned?" />
        <input type="date" id="calendar">
      </div>
  
      <input type="submit" id="new-task-submit" value="Add task" />
    </form>
  </header>
  
  <main>
    <section class="task-list">
      <h2>Tasks</h2>
      
      <div id="tasks">
        <!--<button class = "sort">Sort</button>
              <div class="task">
                      <div class="content">
                          <input 
                              type="text" 
                              class="text" 
                              value="A new task"
                              readonly>
                      </div>
                      <div class="actions">
                          <button class="edit">Edit</button>
                          <button class="delete">Delete</button>
                      </div>
                  </div>--> 
                
      </div>
    </section>
  </main>

    
</body>
</html>

JS

/************************************
 * creates objct of elements needed *
 ************************************/
 
 const elements = {
    form: document.querySelector("#new-task-form"),
    input: document.querySelector("#new-task-input"),
    list: document.querySelector("#tasks"),
    cal: document.querySelector("#calendar")
}

/****************************
 * Generates an ID for task *
 ****************************/

 const createId = () => `${Math.floor(Math.random() * 10000)}-${new Date().getTime()}`


/**********************************************
 * function that creates the HTML elements *
 **********************************************/

 const createTask = () => {
    const id = createId()
    const task = elements.input.value;
    const date = elements.cal.value;

    if(!task && !date) return alert("Please fill in task and select date");
    if(!task) return alert("Please fill in task");
    if(!date) return alert("Please select date");

    const tasks = document.createElement("div");

    tasks.innerHTML = `
    <button class = "sort">Sort</button>
    <div class="task" data-id = "${id}">
        <div class="content">
            <input type ="checkbox" class="tick">
            <input type ="text" class = "text" id = "text" readonly>${task}
            <label class = "due-date" for ="text">${date}</label>
            <input type ="date" class = "date" id = "date">
        </div>

        <div class = "actions">
            <button class="edit" data-id="${id}">Edit</button>
            <button class="delete" data-id="${id}">Delete</button>
        </div>
    </div>
    `
    elements.list.appendChild(tasks)
    return tasks
}


/**************************************************************
 * Event that listens for the edit,save and delete buttons    *
 **************************************************************/

elements.list.addEventListener('click',event => {
    const {target} = event
    const {id} = target.dataset
    const task = id ? document.querySelector('[data-id="${id}"]'):null;
    
    
    const type = {
        edit: event.target.classList.contains('edit'),
        delete: event.target.classList.contains('delete')
    }

    const isFromSaveLabel = target.innerText.toLowerCase() === 'save'

    if(task && type.edit && isFromSaveLabel){
        const text = task.querySelector('.text')
        target.innerText = 'Edit'
        text.addAttribute('readonly')
        return
    };

    if(task && type.edit){
        const text = task.querySelector('.text')
        target.innerText = 'save'
        text.removeAttribute('readonly')
        text.focus()
        return
    };

    if(task && type.delete){
        return
    }
});

/*******************************************************************
 * Submits the HTML elements to have the lists submitted and created*
 *******************************************************************/

 const submitHandler = (event) =>{
    event.preventDefault();
    createTask();
}

elements.form.addEventListener("submit", submitHandler);

我在平台上问了很多关于这个的问题,但我发现我问错了问题。如上所述,我需要事件侦听器来定位使用 const tasks = document.createElement("div");

创建的 <div class="task" date-id = "${id}">

原因是当您点击添加任务时,它会创建一个新的 <div class="task" date-id = "${id}"> 例如 ``````` 包含内容 class 以及其中的所有内容。

PS:对于冗长的代码表示歉意,这是必要的,这样您才能全面了解问题和问题

会不会是因为你在tasks.innerHTML上使用了“date-id”,但是使用了“data-编号”在

const task = id ? document.querySelector('[data-id="${id}"]'):null;

好的,我在事件侦听器中发现了一些问题:

  • queryselector 不是模板文字,因此 ${id} 不起作用。
  • “addAttribute”是错误的。 “setAttribute”是正确的。

修复后编辑并保存作品。

/**************************************************************
 * Event that listens for the edit,save and delete buttons    *
 **************************************************************/

elements.list.addEventListener('click',event => {
    const {target} = event
    const {id} = target.dataset
    const task = id ? document.querySelector(`[data-id="${id}"]`):null;

    const type = {
        edit: event.target.classList.contains('edit'),
        delete: event.target.classList.contains('delete')
    }

    const isFromSaveLabel = target.innerText.toLowerCase() === 'save'

    if(task && type.edit && isFromSaveLabel){
        const text = task.querySelector('.text')
        target.innerText = 'Edit'
        text.setAttribute('readonly', 'true')
        return
    };

    if(task && type.edit){
        const text = task.querySelector('.text')
        target.innerText = 'save'
        text.removeAttribute('readonly')
        text.focus()
        return
    };

    if(task && type.delete){
        return
    }
});

而对于错误,它可能是扩展中的错误。