jquery如何删除<tr>标记

jquery how to remove both the <tr> tag on click?

本文关键字:lt gt 标记 tr 何删除 删除 jquery      更新时间:2023-09-26

我有一个checkbox,它有id-当我选择checkbox-es并单击button时,tr标记应该被删除;当我选择多个checkbox-es时,两个tr标签都应该被移除,但问题是当我选择多重checkbox-es时,只有tr标签属于第一个id被移除。

我已经尝试了以下代码

jQuery

<script>
    function getsample(val) {
        $(function () {
            checkboxid = $('input[name="chk"]:checked').map(function () {
                return this.id
            }).get();
        });
        $("#" + checkboxid).closest('tr').remove();
    }
</script>

HTML

<html>
<body>
    <table>
        <tbody>
        <thead>
            <tr>
                <th>UserName</th>
                <th>Role</th>
                <th>Department</th>
                <th>Semester</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>student15</td>
                <td>Student</td>
                <td>CS</td>
                <td>2</td>
                <td>arung@gmail.com</td>
                <td><input name="chk" type="checkbox" id="sam1"></td>
            </tr>
            <tr>
                <td>student16</td>
                <td>Student</td>
                <td>CS</td>
                <td>2</td>
                <td>arung@gmail.com</td>
                <td><input name="chk" type="checkbox" id="sam2"></td>
            </tr>
        </tbody>
    </table>
    <input type="button" onclick="getsample()" id="button" value="Submit">
</body>
</html>

当我在map函数内使用$("#"+this.id).closest('tr').remove();时,所有选定的tr标签都会被删除,但我需要在map函数外调用checkbox id

帮帮我,提前谢谢。

getsample()函数更改为以下内容。

function getsample(val) {
    $('input[name="chk"]:checked').closest('tr').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <thead>
        <tr>
            <th>UserName</th>
            <th>Role</th>
            <th>Department</th>
            <th>Semester</th>
            <th>Email</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>student15</td>
            <td>Student</td>
            <td>CS</td>
            <td>2</td>
            <td>arung@gmail.com</td>
            <td><input name="chk" type="checkbox" id="sam1"></td>
        </tr>
        <tr>
            <td>student16</td>
            <td>Student</td>
            <td>CS</td>
            <td>2</td>
            <td>arung@gmail.com</td>
            <td><input name="chk" type="checkbox" id="sam2"></td>
        </tr>
    </tbody>
</table>
<input type="button" onclick="getsample()" id="button" value="Submit">

您可以直接循环通过选中的复选框,并使用$(this).closest("tr") 删除父tr

$("#button").click(function() {
  $("[name='chk']:checked").each(function() {
    $(this).closest("tr").remove();
  });
});

Fiddle

您可以使用jquery来选择所有以id"sam"(或名称等于或以"chk"开头)开头的输入字段,从而删除所有<tr>标记。这可以用$('[id^="sam"]:checked')来完成,其中"id^"代表"以开头的id"。您也可以删除"^"以进行完全匹配,或者将"name"代替id。

正在工作的plunker可以在这里找到。