JavaScript数组动态添加和删除数据相关的问题

在做日志批量下载的功能,假设有四条日志,每条日志有一个单选框checkbox,checkbox的id和日志列表的id相对应。想要实现的效果是:选中checkbox后将被选中的日志的id存到一个数组中,取消选中后该将数组中对应的id删除。添加id进数组已经完成了,取消某一条的checkbox选中后如何也让数组中对应的id删除。

img

搞定

img

另一个问题已经帮你解决了哈

你可以加个判断,如果该单选框被选中后,添加一个变量假如是isselected,每次点击后都对这个变量作判断,加入了数组,设置true,未加入设置为false

删除可以用filter数组进行一个过滤


<!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>日志列表</title>
</head>

<body class="bd">
    <div class="mainDiv">
        <div class="div-2">
            <table id="tab" class="tab">
                <thead class="tab-head">
                    <tr>
                        <td style="width:8%;">选择</td>
                        <td style="width:47%;">文件名称</td>
                        <td style="width:30%;">更新时间</td>
                        <td style="width:15%;">文件大小</td>
                    </tr>
                </thead>
                <tbody class="tab-body" id="tbody">
                    <tr>
                        <td><input type="checkbox" id="1"></td>
                        <td>A</td>
                        <td>2022</td>
                        <td>10KB</td>
                    </tr>

                    <tr>
                        <td><input type="checkbox" id="2"></td>
                        <td>B</td>
                        <td>2022</td>
                        <td>10KB</td>
                    </tr>
                    <tr>
                        <td><input type="checkbox" id="3"></td>
                        <td>C</td>
                        <td>2022</td>
                        <td>10KB</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</body>

<script>
    function checkStatu() {
        var selectedDom = [];
        document.getElementById("tbody").addEventListener("click", function (event) {
            event = event || window.event;
            if (event.target.type == "checkbox") {
                selectedDom.push(event.target.id);
                    selectedDom.push(event.target.id);
                    var newSelectedDom = selectedDom.filter(function (item, index) {
                        return selectedDom.indexOf(item) === index;
                    });
                console.log(newSelectedDom)
            }
           
        }, false)
    }
    checkStatu();
</script>
</html>