如何删除克隆的行

时间:2019-05-30 21:33:47

标签: javascript

尝试制作购物车。我创建了一个包含产品的表(每行包含一个项目,其价格和一个用于选择它的按钮)。使用js,当您单击某个项目的按钮时,它将克隆该项目的整个行,并将克隆放置在第二个表(即购物篮)中。我想在单击第二个表的按钮时删除它的一个克隆行。这不是要删除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>

1 个答案:

答案 0 :(得分:1)

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>