Saya membuat halaman web 'yang harus dilakukan' dan di sana saya menambahkan semua tugas ke dalam array. Sekarang, untuk menghapus tugas yang sudah ditambahkan, saya telah mencoba menggunakan Splice, Shift dan menghapus tetapi tidak ada yang menghapus tugas pada indeks yang diinginkan serta kartu dari UI. Akan berterima kasih atas bantuan apa pun karena saya benar-benar pemula.

let addbtn=document.getElementById('addbtn')
addbtn.addEventListener('click',addnotes)
var nodeadd=[];

var arr;
var result;
var unique;
function addnotes(){
    console.log("I am adding");
    let addtxt=document.getElementById('addTxt');
    nodeadd.push(addtxt.value);
  unique=[...new Set(nodeadd)];
   //arr=unique.join("").trim().split(' ');
  // result=unique.filter((item)=>item!=' ');
   console.log("I am texting",unique);
   addtxt.value="";
 showNotes();
}

function showNotes(){
    let html="";
    console.log("I am getting",unique);
   //result=unique.join("").trim().split(' ');
    //const result=unique.filter((item)=>item!=' ');
    result = unique.filter(unique => unique.trim().length > 0);
    console.log("I am result",result);
     
    result.forEach((element,index) => {
        console.log("I am calling")
        console.log(element,index);
        html+=`<div class="nodeCard my-2 mx-2 card" style="width: 18rem;">
        <div class="card-body">
          <h5 class="card-title">${index}</h5>
          <p class="card-text">${element}</p>
          <button  id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete note</a>
        </div>
      </div>`
    });
   let ele=document.getElementById('notes');
   if(result.length!=0){
       ele.innerHTML=html;
   }
  }
  function deleteNote(index){
   for(let i=0;i<result.length;i++){
     //console.log("I am  logging");
     //console.log("index",i);
     //console.log("indexing",index);
     console.log(index);
     if(i==index){
       //console.log("I am getting index",i,index);
       result.splice(i,1);
     // result.shift();
     }
   }

  }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              Dropdown
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
              <li><a class="dropdown-item" href="#">Action</a></li>
              <li><a class="dropdown-item" href="#">Another action</a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item" href="#">Something else here</a></li>
            </ul>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled">Disabled</a>
          </li>
        </ul>
        <form class="d-flex">
          <input class="form-control me-2" id="search" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>
  <div class="container my-3">
    <h1>Welcome to magic notes</h1>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Add a note</h5>
        <div class="mb-3">
          <label for="exampleFormControlTextarea1" class="form-label">Example textarea</label>
          <textarea class="form-control" id="addTxt" rows="3"></textarea>
        </div>
        <button  class="btn btn-primary" id="addbtn">Add note</a>
      </div>
    </div>
    <h2>Notes</h2>
    <hr/>
    <div id="notes" class="row container-fluid">
    </div>
    <script src="app.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-W8fXfP3gkOKtndU4JGtKDvXbO53Wy8SZCQHczT5FMiiqmQfUpWbYdTil/SxwZgAN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"></script>
</body>
</html>
1
Sohana Gupta 1 Oktober 2021, 09:43

3 jawaban

Jawaban Terbaik

Anda perlu menambahkan ID ke elemen baru dan kemudian menghapusnya dengan ID ini dari DOM. Periksa tiga baris // komentar sebaris.

Adapun array, pada dasarnya splice benar, tetapi Anda harus menangani elemen array terakhir dan tidak melupakan array nodeadd

TETAPI - perlu diingat, bahwa Anda menghapus catatan dengan ID mereka, jadi jika Anda pertama kali menghapus id 0, maka setelah penyambungan, id sebelumnya 1 Anda akan menjadi id 0, tetapi tombol Anda akan merujuk ke id 1 - ini akan mencegah elemen dihapus. Coba perbarui kode ini, jadi id elemen akan disegarkan setiap kali Anda menghapus catatan.

let addbtn=document.getElementById('addbtn')
addbtn.addEventListener('click',addnotes)
var nodeadd=[];

var arr;
var result;
var unique;
function addnotes(){
    console.log("I am adding");
    let addtxt=document.getElementById('addTxt');
    nodeadd.push(addtxt.value);
  unique=[...new Set(nodeadd)];
   //arr=unique.join("").trim().split(' ');
  // result=unique.filter((item)=>item!=' ');
   console.log("I am texting",unique);
   addtxt.value="";
 showNotes();
}

function showNotes(){
    let html="";
    console.log("I am getting",unique);
   //result=unique.join("").trim().split(' ');
    //const result=unique.filter((item)=>item!=' ');
    result = unique.filter(unique => unique.trim().length > 0);
    console.log("I am result",result);
     
    result.forEach((element,index) => {
        console.log("I am calling")
        console.log(element,index);
        //
        // Add ID to html element
        //
        html+=`<div id="noteId-${index}" class="nodeCard my-2 mx-2 card" style="width: 18rem;">
        <div class="card-body">
          <h5 class="card-title">${index}</h5>
          <p class="card-text">${element}</p>
          <button  id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete note</a>
        </div>
      </div>`
    });
   let ele=document.getElementById('notes');
   if(result.length!=0){
       ele.innerHTML=html;
   }
   //
   // Log results
   //
   console.log(result);
  }
  function deleteNote(index){
   for(let i=0;i<result.length;i++){
     //console.log("I am  logging");
     //console.log("index",i);
     //console.log("indexing",index);
     console.log(index);
     if(i==index){
       //console.log("I am getting index",i,index);
       //
       // Check if last result
       //
       if(result.length === 1) {
         result.splice(-1);
         // also splice nodeadd array
         nodeadd.splice(-1);
       } else {
         result.splice(i,1);
         // also splice nodeadd array
         nodeadd.splice(i,1);
       }
       break;
     // result.shift();
     }
   }
   //
   // Log results
   //
   console.log(result);
   //
   // Remove element from DOM by ID
   //
   document.getElementById(`noteId-${index}`).remove();
   //
   //
   //
  }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              Dropdown
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
              <li><a class="dropdown-item" href="#">Action</a></li>
              <li><a class="dropdown-item" href="#">Another action</a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item" href="#">Something else here</a></li>
            </ul>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled">Disabled</a>
          </li>
        </ul>
        <form class="d-flex">
          <input class="form-control me-2" id="search" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>
  <div class="container my-3">
    <h1>Welcome to magic notes</h1>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Add a note</h5>
        <div class="mb-3">
          <label for="exampleFormControlTextarea1" class="form-label">Example textarea</label>
          <textarea class="form-control" id="addTxt" rows="3"></textarea>
        </div>
        <button  class="btn btn-primary" id="addbtn">Add note</a>
      </div>
    </div>
    <h2>Notes</h2>
    <hr/>
    <div id="notes" class="row container-fluid">
    </div>
    <script src="app.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-W8fXfP3gkOKtndU4JGtKDvXbO53Wy8SZCQHczT5FMiiqmQfUpWbYdTil/SxwZgAN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"></script>
</body>
</html>
1
tarkh 1 Oktober 2021, 07:31

Gunakan arr.filter alih-alih splice. Anda juga dapat membaca dokumen di arr.filter dari MDN ini akan membantu Anda.

Sebagai contoh

const updatedarr = oldarr.filter((item) => item.id ===id )
// filter returns a new array containing the elements that meet the condition in the function passed to it
2
connexo 1 Oktober 2021, 08:37

Apakah Anda mencoba .indexOf()?

arr.splice(arr.indexOf(ele), 1);
0
Azure 1 Oktober 2021, 06:53