其他分享
首页 > 其他分享> > JS实现购物车添加以及删除效果

JS实现购物车添加以及删除效果

作者:互联网

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      *{margin: 0;padding: 0;}
      table{margin: 0 auto;width: 400px;}
      th,td{width: 100px;border-spacing: 0;border-collapse:collapse;text-align: center;}
    </style>
   </head>
  <body>
    <button type="button" id="btn">添加表格行</button>
    <table border="1" cellspacing="0">
      <thead>
        <tr>
          <th>产品名称</th>
          <th>价格</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>农夫山泉</td>
          <td>¥2.00</td>
          <td><a href="#">删除</a></td>
        </tr>
        <tr>
          <td>农夫山泉</td>
          <td>¥2.00</td>
          <td><a href="#">删除</a></td>
        </tr>
        <tr>
          <td>农夫山泉</td>
          <td>¥2.00</td>
          <td><a href="#">删除</a></td>
        </tr>
        <tr>
          <td>农夫山泉</td>
          <td>搬运工</td>
          <td><a href="#">删除</a></td>
        </tr>
      </tbody>
    </table>
    <script type="text/javascript">
      var btn = document.getElementById("btn");
      var tbody = document.querySelector("tbody");
      var tr;
      var a = document.querySelectorAll("a");
      console.log(a)
      for (i = 0; i < a.length; i++) {
        a[i].onclick = function() {
        this.parentNode.parentNode.remove();
        }
      }
      btn.onclick = function() {
        tr = document.createElement("tr");
        tr.innerHTML = "<td>农夫山泉</td><td>搬运工</td><td><a href='#'>删除</a></td>"
        tbody.appendChild(tr)
        a = document.querySelectorAll("a");
        console.log(a)
        for (i = 0; i < a.length; i++) {
          a[i].onclick = function() {
            this.parentNode.parentNode.remove();
          }
        }
      }
</script>
</body>
</html>

标签:删除,农夫山泉,tr,parentNode,JS,添加,var,document,购物车
来源: https://www.cnblogs.com/mizuno0237/p/11432214.html