简体   繁体   English

如何删除克隆的行

[英]How to remove a cloned row

Trying to make a shopping cart. 试图做一个购物车。 I've created a table containing products (each row contains an item, its price, and a button to select it). 我创建了一个包含产品的表(每行包含一个项目,其价格和一个用于选择它的按钮)。 With js, when you click on a button of an item it clones the entire row of this item and put the clone in a second table (which is the shopping basket). 使用js,当您单击某个项目的按钮时,它将克隆该项目的整个行,并将克隆放置在第二个表(即购物篮)中。 I would like to remove a cloned row of the second table when clicking on its button. 我想在单击第二个表的按钮时删除它的一个克隆行。 It's not about remove the DOM parent, because the button parent is a td and not the entire tr which I would like to delete. 这与删除DOM父级无关,因为按钮父级是td,而不是我要删除的整个tr。

 let basket = document.getElementById("products_cart") let buttons = document.querySelectorAll('.item_button'); for (button of buttons) { button.addEventListener('click', cloneLine); } function cloneLine(e) { let td = e.target.parentNode; let tr = td.parentNode; let clone = tr.cloneNode(true); basket.appendChild(clone); clone.querySelector('.item_button').textContent = "-"; } 
 <h1>CHOOSE</h1> <table id="starters"> <tr> <th>PRODUCT</th> <th>PRICE</th> <th>ADD TO CART</th> </tr> <tr> <td>Cherry</td> <td>6</td> <td><button class="item_button">+</button></td> </tr> <tr> <td>Peach</td> <td>8</td> <td><button class="item_button">+</button></td> </tr> <tr> <td>Strawberry</td> <td>12</td> <td><button class="item_button">+</button></td> </tr> </table> <h1>YOUR CHOICE</h1> <table id="products_cart"> </table> 

 let basket = document.getElementById("products_cart") let buttons = document.querySelectorAll('.item_button'); for (button of buttons) { button.addEventListener('click', cloneLine); } function cloneLine(e) { let td = e.target.parentNode; let tr = td.parentNode; let clone = tr.cloneNode(true); basket.appendChild(clone); clone.querySelector('.item_button').textContent = "-"; clone.querySelector('.item_button').addEventListener("click", function(){ basket.removeChild(clone); }); } 
 <h1>CHOOSE</h1> <table id="starters"> <tr> <th>PRODUCT</th> <th>PRICE</th> <th>ADD TO CART</th> </tr> <tr> <td>Cherry</td> <td>6</td> <td><button class="item_button">+</button></td> </tr> <tr> <td>Peach</td> <td>8</td> <td><button class="item_button">+</button></td> </tr> <tr> <td>Strawberry</td> <td>12</td> <td><button class="item_button">+</button></td> </tr> </table> <h1>YOUR CHOICE</h1> <table id="products_cart"> </table> 

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

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