动态生成表格

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
                width: 500px;
                margin: 100px auto;
                border-collapse: collapse;
                text-align: center;
            }

    </style>
</head>
<body>
    姓名:<input type="text" id="name"><br>
    科目:<input type="text" id="sbj"><br>
    成绩:<input type="text" id="grade"><br>
    
    <input type="button" onclick="add()" value="添加">
    <table cellspacing="0" border="1">
        <thead>
            <tr>
                <th>姓名</th>
                <th>科目</th>
                <th>成绩</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="lis"></tbody>
    </table>

<script>
   

   function add(){
    
     var name=document.getElementById("name").value;
     var sbj=document.getElementById("sbj").value;
     var grade=document.getElementById("grade").value;

      var tr=document.createElement("tr");

      var td1=document.createElement("td");
      td1.innerHTML=name;

      var td2=document.createElement("td");
      td2.innerHTML=sbj;

      var td3=document.createElement("td");
      td3.innerHTML=grade;

      var td4=document.createElement("td");
      var a=document.createElement("a");
      a.setAttribute("href","javascript:void(0)");
      a.setAttribute("onclick","del(this)");
      a.innerHTML="删除";
      td4.appendChild(a);

      tr.appendChild(td1);
      tr.appendChild(td2);
      tr.appendChild(td3);
      tr.appendChild(td4);

      var lis=document.getElementById("lis");
      lis.appendChild(tr);
   }


   function del(a){
    var tr=a.parentNode.parentNode;
    var lis=document.getElementById("lis");
    lis.removeChild(tr);
   }
</script>
</body>
</html>
上一篇:关于 SAP 电商云 Spartacus UI 路由 routes 配置的数据源问题


下一篇:append vs appendChild 的差别