利用javascript实现表格的删除

2023-09-21 08:02:53
<!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>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    body{
        display: flex;
        justify-content: center;
        align-items: center;
        height: 80vh;
    }
    table{
        width: 300px;
        text-align: center;
    }
    tr{
        background-color: blanchedalmond;
    }

</style>
<body>
    <table border="1" cellspacing='0'>
        <thead>
        <tr>
            <th>姓名</th>
            <th>科目</th>
            <th>成绩</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
<script>
    var datas=[
        {
            name:'大炜',
            subject:'JavaScript',
            score:99,
        },
        {
            name:'林烨',
            subject:'JavaScript',
            score:88
        },
        {
            name:'善隆',
            subject:'JavaScript',
            score:77
        },
        {
            name:'宇杨',
            subject:'JavaScript',
            score:66
        }
    ];
    var tbody=document.querySelector('tbody');
    for(var i=0;i<datas.length;i++){
        var tr=document.createElement('tr');
        tbody.appendChild(tr);
        for(var key in datas[i]){
            var td=document.createElement('td');
            td.innerHTML=datas[i][key];
            tr.appendChild(td);
        }
        
        var td =document.createElement('td');
        td.innerHTML='<a href="javascript:;">删除</a>';
        tr.appendChild(td);
    }
    var as=document.querySelectorAll('a');
    for(var i=0;i<as.length;i++){
        as[i].onclick=function(){
            tbody.removeChild(this.parentNode.parentNode);
        }
    }
</script>
</body>
</html>
  • 作者:小韦的案例小窝
  • 原文链接:https://blog.csdn.net/weiyuyang250/article/details/120735811
    更新时间:2023-09-21 08:02:53