简体   繁体   English

仅由 js 单击时从数组中删除一项

[英]Remove one item from an array when clicked by only js

I am new to JavaScript.我是 JavaScript 的新手。 I have a small code that creates list from input and then adds it to an array.我有一个小代码,它从输入创建列表,然后将其添加到数组中。 I am able to remove one item from the DOM when the item is clicked, but I couldn't remove it from the array.单击该项目时,我可以从 DOM 中删除一项,但无法将其从数组中删除。

I tried to use array.splice(item, 1)我尝试使用array.splice(item, 1)

lists.addEventListener("click", function (e) {
    e.target.closest("li").remove();
    userInputArr.splice(item, 1);});

But it removes the entire array sometime, and sometime removes the last item.但它有时会删除整个数组,有时会删除最后一项。 when I console log the code, it looks like I clicked 3 or 4 times on the list even though I just clicked once.当我控制台记录代码时,看起来我在列表上单击了 3 或 4 次,即使我只单击了一次。 I have no idea what's wrong.我不知道出了什么问题。 this is the entire code:这是整个代码:

const lists = document.querySelector(".lists");
const userInput = document.querySelector(".add-note");
const addBtn = document.querySelector(".add-btn");
const item = document.querySelectorAll(".list");

userInputArr = [];

function addNote() {
  if (userInput.value < 1) {
    return;
  }
  lists.insertAdjacentHTML(
    "afterbegin",
    `<li class='list'>${userInput.value}</li>`
  );
  userInputArr.push(lists);

  lists.addEventListener("click", function (e) {
    e.target.closest("li").remove();
    userInputArr.splice(item, 1);
  });
  userInput.value = "";
}

addBtn.addEventListener("click", function () {
  addNote();
});

Code is totally meaningless代码完全没有意义

1) 1)

userInputArr.push(lists)

why you push the same element all the time?为什么你总是推同一个元素? As lists refers to the first and the only element with class 'lists'?列表是指第一个也是唯一一个带有 class '列表'的元素?

2) 2)

userInputArr.splice(item, 1)

please watch carefully what splice does?请仔细观察接头是做什么的? The first argument is number, but you pass a collection of elements with class 'list'.第一个参数是数字,但您使用 class 'list' 传递元素集合。 But i camn not even suggest which element should be removed as it contains the same element as i mentioned in first point但我什至不建议应该删除哪个元素,因为它包含与我在第一点中提到的相同元素

3) You do not need this array at all 3) 你根本不需要这个数组

So right approach is something like this所以正确的方法是这样的

const lists = document.querySelector(".lists");

// just once create listener, no need to do it each time
lists.addEventListener("click", function (e) {
  // if you want to remove clicked item then
  if (e.target.tagName === 'LI') e.target.remove(); 

  // but if you want to remove the first one then uncomment line
  // if (this.children[0]) this.children[0].remove()
});

const userInput = document.querySelector(".add-note");
const addBtn = document.querySelector(".add-btn");

///////////////////////////////////////////////////
// item is meaninglee here, so delete this line
// const item = document.querySelectorAll(".list");

//////////////////////
// array is useless too, delete this line
// userInputArr = [];

function addNote() {
  // check if it is number
  if (isNaN(userInput.value) || Number(userInput.value < 1)) {
    return;
  }

  lists.insertAdjacentHTML(
    "afterbegin",
    `<li class='list'>${userInput.value}</li>`
  );

  userInput.value = "";
}

addBtn.addEventListener("click", function () {
  addNote();
});

 const items = (() => { const _items = {}; let key = 0; return { put(value) { _items[key++] = value; console.log("Added", this.all()); return key - 1; }, remove(key) { delete _items[key++]; console.log("Removed", this.all()); }, all(asArray = true) { return asArray? Object.values(_items): {..._items }; } } })(); const inputEl = document.querySelector(".input"); const itemsEl = document.querySelector(".items"); const addBtn = document.querySelector(".btn-add"); addBtn.addEventListener("click", () => { const value = inputEl.value.trim(); if (.value;length) return. const key = items;put(value). const li = document;createElement("li"). li;textContent = value. li.dataset;key = key. itemsEl;append(li). inputEl;value = ""; }). itemsEl,addEventListener("click". (e) => { const li = e.target;closest("li"). items.remove(li.dataset;key). li;remove(); });
 <input type="text" class="input"> <button class="btn-add">Add</button> <ul class="items"></ul>

Run code & View in full screen.全屏运行代码和查看。

use shift() userInputArr.shift() you are also getting double clicks because your addNote() function contains an event listener lists.addEventListener and it's executed by another event listner addBtn.addEventListener you should probably move lists.addEventListener out of the addNote function使用shift() userInputArr.shift()你也会得到双击,因为你的addNote() function 包含一个事件监听lists.addEventListener并且它由另一个事件监听器addBtn.addEventListener执行你可能应该将lists.addEventListener移出addNote ZC1C425268E68385D1AB5074C14F

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

相关问题 当指定为仅删除一次时,拼接将从数组中删除多个项 - Splice is removing more that one item from array when specified to only remove once 从数组列表中添加或删除单击的项目 - Add or Remove clicked Item from the Array list 即使存在重复项,也只能从JS数组中删除一项 - Remove only 1 item from JS Array even if duplicates exist 当单击另一个数组中的另一个单独的项目,同时又从第一个数组中删除该项目时,从一个数组中随机显示项目? - Show item at random from one array when another separate item in a different array is clicked while also removing that item from the first array? 仅使用单词从数组中删除项目 - Remove Item from Array using only word 仅单击一个时如何删除所有按钮的事件侦听器 - How to remove the event listeners of all buttons when only one is clicked 将索引从子组件发送到父组件以删除v-for-VUE.JS 2中的数组项 - Send index from child component to the parent one to remove array item in v-for - VUE.JS 2 在 Vanilla JS 中单击父级时仅打开一个子菜单 - Open only one submenu when clicked on the parent in Vanilla JS 仅显示阵列中的一项 - Only displaying one item from Array 将另一个项添加到数组时从数组中删除项 - remove item from array when another item is added to array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM