码迷,mamicode.com
首页 > Web开发 > 详细

原生js实现table的增加删除

时间:2020-06-01 18:03:25      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:删除   var   width   child   utf-8   code   aci   check   click   

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .table,
    .table tr,
    .table td {
      border: 1px solid #000000;
    }

    #tables {
      display: none;
    }

    .table input {
      outline: none;
      border: 0;
      background-color: rgba(0, 0, 0, 0);
    }
  </style>
</head>

<body>
  <div class="container">
    <div>
      <label for="showTable">显示<input type="radio" name="isShow" id="showTable" onclick="clickShow()"></label>
      <label for="hideTable">隐藏 <input type="radio" checked name="isShow" id="hideTable" onclick="clickHide()"></label>
    </div>
    <div id="tables">
      <div>
        <button onclick="addTr()">添加</button>
        <button onclick="deleteTr()">删除</button>
      </div>
      <table id="table" class="table" cellspacing="0">
        <tr>
          <td><input type="checkbox" class="checkbox"></td>
          <td>
            <input type="text">
          </td>
          <td>
            <input type="text">
          </td>
          <td>
            <input type="text">
          </td>
        </tr>
      </table>
    </div>
  </div>
</body>
<script>
  function addTr() {
    var tr = document.createElement("tr");
    var td = null;
    var input = null;
    for (let i = 0; i < 4; i++) {
      input = document.createElement(‘input‘);
      if (i == 0) {
        input.type = "checkbox";
        input.className = "checkbox";
      }
      td = document.createElement(‘td‘);
      td.appendChild(input);
      tr.appendChild(td);
    }
    document.getElementById("table").children[0].appendChild(tr);
  }

  function deleteTr() {
    var box = document.getElementsByClassName(‘checkbox‘);
    var len = box.length;
    var parent = null;
    for (var i = len - 1; i > -1; i--)
      if (box[i].checked) {
        parent = box[i].parentNode.parentNode;
        parent.remove();
      }
  }

  function clickShow() {
    document.getElementById("tables").style.display = "inline-block";
  }

  function clickHide() {
    document.getElementById("tables").style.display = "none";
  }
</script>


</html>

效果图

Document

原生js实现table的增加删除

标签:删除   var   width   child   utf-8   code   aci   check   click   

原文地址:https://www.cnblogs.com/chendada/p/13026474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!