简体   繁体   English

纯 javascript 从模态 window(购物车)中删除元素

[英]Removing Element from Modal window (shop cart) by pure javascript

so I try to make some simple content of modal window as a shopping cart only using js, and there is a problem with delete of each item by "x" after I add them on the cart, I use event.target, but at that stage it gives me an error as "null", it is in the last row of the code.所以我尝试将模态 window 的一些简单内容作为仅使用 js 的购物车,并且在我将它们添加到购物车后,通过“x”删除每个项目存在问题,我使用 event.target,但在那阶段它给我一个错误为“null”,它位于代码的最后一行。 Dont be strict, its my first code:) so each time I insert in cart不要严格,这是我的第一个代码:) 所以每次我插入购物车

cartItems.innerHTML += `<div class="modal-items-flex ">
<div>
<h2> Item Price: ${itemPrice} </h2>
<h2 class="underscore">Item Name: ${itemTitle} </h2>
</div>
<div class="modal-item-delete">+</div>
</div>`

let removeButton = document.querySelector(".modal-item-delete");

removeButton.onclick=function(e){                               
  e.target.parentElement.remove();
} 

I would not attach a new event-listener to each item, but instead would delegate the event-handling to the parent, for example:我不会为每个项目附加一个新的事件侦听器,而是将事件处理委托给父项,例如:

cartItems.addEventListener('click', (e) => {
  const btn = e.target.closest('.modal-item-delete');
  if (!btn) return;
  btn.parentElement.remove();
});

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

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