简体   繁体   English

单击按钮时如何删除表格中的行? 使用Javascript

[英]How to delete a row in the table when I click on a button? Using Javascript

HTML from with table and button: 带表和按钮的HTML:

<div>
                <h1>Info</h1>
                <form>
                    <table id="t">
                        <tr>
                            <th></th>
                            <th>index</th>
                            <th>name</th>
                            <th>job</th>
                            <th>date</th>
                            <th>department</th>
                        </tr>
                        <tr>
                            <td><input type="checkbox"></td>
                            <td>1</td>
                            <td>Alex</td>
                            <td>Hacker</td>
                            <td>100000000000000000</td>
                            <td>2</td>
                        </tr>
                    </table>
                    <br/>
                    <input type="submit" value="delete" onclick="deleteRow()">
                </form>
        </div>

I want to remove rows, which have establishes checkbox. 我想删除已建立复选框的行。 Delete should be at the click of a button. 删除应该是单击按钮。

Javascript function that should delete: 应该删除的Javascript函数:

function deleteRow() {
    let table = document.getElementById('t')
    let boxs = table.getElementsByTagName("input")
    for (i = 0; i < boxs.length; i++){
        if(boxs[i] == true) {
            table.deleteRow((boxs[i].parentNode.parentNode).rowIndex)
        }
    }
}

I debugged this code, the size of the array defined correctly, but doesn't enter to condition. 我调试了这段代码,正确定义了数组的大小,但没有进入条件。

In you code you don't need to change much. 在你的代码中,你不需要做太多改变。 You need to change if statement like below. 您需要更改if语句,如下所示。

From

if(boxs[i] == true) { if(boxs [i] == true){

} }

To

if(boxs[i].checked == true) { if(boxs [i] .checked == true){

} }

Because box[i] is object. 因为box [i]是对象。 So If you want to get the check status you need to call boxs[i].checked. 因此,如果您想获得检查状态,您需要调用boxs [i] .checked。 This will give you true/false. 这会给你真/假。

 function deleteRow() { let table = document.getElementById('t') let boxs = table.getElementsByTagName("input") for (i = 0; i < boxs.length; i++){ if(boxs[i].checked == true) { table.deleteRow((boxs[i].parentNode.parentNode).rowIndex) } } return false; } 
 <div> <h1>Info</h1> <form onsubmit="return deleteRow()"> <table id="t"> <tr> <th></th> <th>index</th> <th>name</th> <th>job</th> <th>date</th> <th>department</th> </tr> <tr> <td><input type="checkbox"></td> <td>1</td> <td>Alex</td> <td>Hacker</td> <td>100000000000000000</td> <td>2</td> </tr> </table> <br/> <input type="submit" value="delete"> </form> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM