如何让我的 X 按钮删除数组中的特定对象?

Posted

技术标签:

【中文标题】如何让我的 X 按钮删除数组中的特定对象?【英文标题】:how do i make my X button delete the specific object inside array? 【发布时间】:2021-06-25 14:53:53 【问题描述】:

我第一次在这里发帖时,我对 Web 开发和编程非常陌生。

我目前正试图让我的 X 按钮删除数组中的特定对象。 它是这样的 - 用户可以制作 3 个黄色笔记 - 用户将值存储为一个对象,并且函数 displayTasks() 刷新了 displayTasks() 内部的笔记 - 当用户按下 X 时它触发 onclick( ) 需要删除这个特定对象,但它总是删除数组中的最后一个音符和对象 如何让它选择 div 内的确切对象? 我希望我清楚这一点! 谢谢提前!

those are the notes

class Task
    constructor(mytask,mydate,mytime)
        this.task=mytask;
        this.date=mydate;
        this.time=mytime;
    
   


const myTask = document.getElementById("task")
const date = document.getElementById("date")
const time = document.getElementById("time")
const save = document.getElementById("save")
const reset = document.getElementById("reset")
const paragraph = document.getElementById("mypara")
const taskRow = document.getElementById("taskRow")
const tasks = []


function addTask() 
    // 1. add new note to tasks array
    // 2. call displayNotes()
    if (tasks.length > 2) 
        return alert("Too Many Notes please Complete One");
    
    tasks.push(new Task(myTask.value, date.value, time.value));

    resetTask();
    displayTasks();


function resetTask() 
    myTask.value = '';
    date.value = '';
    time.value = '';

function deleteTask(index) 
    tasks.splice(index, 1);
    displayTasks();


function displayTasks() 
    // 1. delete all inner html in tasks row
    // 2. for each element in tasks array: add a task html to the tasks row
    taskRow.innerHTML = "";

    for (task in tasks) 
       
            console.log(tasks)
        let taskDiv = document.createElement("div");
        taskDiv.setAttribute("class", "col-sm task");

        let description = document.createElement("p");
        description.setAttribute("class", "description");
        description.innerHTML = `$tasks[task].task<br>`

        let finishDate = document.createElement("div");
        finishDate.setAttribute("class", "date");
        finishDate.innerHTML = `$tasks[task].date`;

        let escape = document.createElement("p");
        escape.setAttribute("class", "escape glyphicon glyphicon-remove");
        escape.innerHTML = `X`;
        escape.onclick = function callback() 
            deleteTask(task);
            console.log(task);
            // escape.onclick = function() 
            //     deleteTask(task);
            //   
        
        taskDiv.appendChild(escape)
        taskDiv.appendChild(description);
        taskDiv.appendChild(finishDate);
        taskRow.appendChild(taskDiv);

    

body 
background-image: url("/jpglibrary/tile.gif");
position: absolute;
left: 450px;

.notes
  position: absolute;

/* .task_input
  overflow-y: auto;

 */

.notesInput
  position: relative;
  padding: 10px;
  margin: 10px;
  background-image: url("jpglibrary/formbg.jpg");
  


.savebutton
  position: absolute;
  left: 500px;
  bottom: 30px;

.resetbutton
  position: absolute;
  left: 500px;
  bottom: 0px;

h1
  font-family: 'cuteFont';
  text-align: center;
  margin-top: 30px;
  font-size: 8ch;   


.innertext
  height: 188px;
  width: 170px;
  position: absolute;
  top: 408px;

.date
  position: absolute;
  padding: 4px;
  bottom: 7px;
  height: 28px;
  width: 100px;
  font-size: 13px;
   

.task
  background-image: url("/jpglibrary/notebg.png");
  background-repeat: no-repeat;
  height: 240px;
  width: 100px;
  padding: 0px;
  animation: fadeIn ease 2s;

.description
  position:absolute;
  top: 40px;
  padding: 3px;
  width: 175px;
  height: 170px ;
  overflow-y: auto;

.escape
  
  padding-left: 160px;
  padding-top: 20px;

@font-face
  font-family: cuteFont;
  src: url("fonts/CuteNotes.ttf");


@keyframes fadeIn 
  0% 
      opacity: 0;
  
  100% 
      opacity: 1;
  
<!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">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>

<body id="main_body">
  <div class='container'>
    <h1>My Task Board</h1>
    <!-- <div class="notes">
      <img src="jpglibrary/formbg.jpg" class="mx-auto d-block">
      <img src="jpglibrary/formbg.jpg" class="mx-auto d-block">
      <img src="jpglibrary/formbg.jpg" class="mx-auto d-block">

    </div> -->
    <div class=notesInput>
      <input type="text" placeholder="My task" id="task" class="task_input">
      <br>
      <div>
        <label>Finish Date <br>
          <input type="date" id="date">
        </label>
      </div>
      <div>
        <label>Finish Time<br>
          <input type="time" id="time">
      </div></label>
      <div class="savebutton">
        <input type="button" value="Save" onclick=addTask() id="save">
      </div>
      <div class="resetbutton">
        <input type="button" onclick="resetTask()" value="Reset" id="reset">
      </div>
    </div>
    <div id="tasksContainer" class="container">
      <div id="taskRow" class="row">

      </div>
    </div>

  </div>

</body>
<script src="Task.js"></script>
<script src="script.js"></script>

</html>

【问题讨论】:

编码说明:除非您实际设置 HTML,否则不要使用 innerHTML。如果您要设置文本,请改用textContent。并且不要添加 &lt;br&gt; 元素,这就是 CSS 的用途。此外,如果您使用正确的 DOM 函数(如 createElement),也请使用正确的事件函数(例如,对 click 事件使用 addEventListener,不要使用旧的 onclick 属性) 【参考方案1】:

您只需要获取点击任务的索引并将该索引提供给 deleteTask()。

escape.addEventListener('click', function callback(e) 
    var child = e.target.parentElement;
    var container = child.parentElement;
    var index = Array.prototype.slice.call(container.children).indexOf(child)
    deleteTask(index);
);

工作示例:

class Task
    constructor(mytask,mydate,mytime)
        this.task=mytask;
        this.date=mydate;
        this.time=mytime;
    


const myTask = document.getElementById("task")
const date = document.getElementById("date")
const time = document.getElementById("time")
const taskRow = document.getElementById("taskRow")
const tasks = []

function addTask() 
    if (tasks.length > 2) 
        return alert("Too Many Notes please Complete One");
    
    tasks.push(new Task(myTask.value, date.value, time.value));
    resetTask();
    displayTasks();

function resetTask() 
    myTask.value = "";
    date.value = "";
    time.value = "";

function deleteTask(index) 
    tasks.splice(index, 1);
    displayTasks();

function displayTasks() 
    taskRow.innerHTML = '';

    for (task in tasks) 
       
        let taskDiv = document.createElement("div");
        taskDiv.setAttribute("class", "col-sm task");

        let description = document.createElement("p");
        description.setAttribute("class", "description");
        description.innerText = `$tasks[task].task`;

        let finishDate = document.createElement("div");
        finishDate.setAttribute("class", "date");
        finishDate.innerText = `$tasks[task].date`;

        let escape = document.createElement("p");
        escape.setAttribute("class", "escape glyphicon glyphicon-remove");
        escape.innerText = 'X';
        
        escape.addEventListener('click', function callback(e) 
            var child = e.target.parentElement;
            var container = child.parentElement;
            var index = Array.prototype.slice.call(container.children).indexOf(child)
            deleteTask(index);
        );
        
        taskDiv.appendChild(escape)
        taskDiv.appendChild(description);
        taskDiv.appendChild(finishDate);
        
        taskRow.appendChild(taskDiv);

    

.container 
    width: 250px;
    text-align: center;

.inputs, #taskRow 
    display: flex;
    flex-direction: row;
    justify-content: space-between;

.task 
    border: 1px solid black;
    text-align: left;

.escape 
    cursor: pointer;
    text-align: right;
    margin: 0;
<div class='container'>

    <h1>My Task Board</h1>
    
    <div class=notesInput>
        <div class="inputs">
            <label for="task">Task</label>
            <input type="text" placeholder="My task" id="task" class="task_input">
        </div>
        <div class="inputs">
            <label for="date">Finish Date</label>
            <input type="date" id="date">
        </div>
        <div class="inputs">
            <label for="date">Finish Time</label>
            <input type="time" id="time">
        </div>
        <div class="inputs">
            <input type="button" onclick="resetTask()" value="Reset" id="reset">
            <input type="button" value="Save" onclick=addTask() id="save">
        </div>
    </div>
    
    <div id="tasksContainer" class="container">
        <div id="taskRow" class="row"></div>
    </div>

</div>

【讨论】:

以上是关于如何让我的 X 按钮删除数组中的特定对象?的主要内容,如果未能解决你的问题,请参考以下文章

如何从特定单击的响应中删除数组中的索引

如何从GoogleMapsAPI中的静态数组中删除特定标记

如何通过typescript中的对象数组删除特定对象

试图让我的删除按钮在 REACT 中工作

如何添加或Java中的数组中删除一个随机数?

如何让我的浏览对话框转到 VBA 中的特定文件夹?