这只会删除表中的第一行.我希望它删除我使用jQuery和html单击的任何行

This will only delete the first row in my table. I would like it to delete whichever row I click on using jQuery & html

本文关键字:删除 jQuery 任何行 单击 html 我希望 一行      更新时间:2023-09-26

我想知道如何删除我单击删除链接的任何表行。现在它只删除一行。

<script type="text/javascript">
        $(function() {
            $("#deleteEvent").click(function(e) {
                $("#drow").remove();
                return false;
            });
    </script>

网页在这里

<div id="students">
        <table>
            <caption>Students</caption>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Student ID</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
            <tr id="drow"><td>John</td><td>Doe</td><td>1234</td><td>john.doe@gmail.com</td><td><a      href="#" id="deleteEvent">Delete</a></td></tr>
            <tr id="drow"><td>Amy</td><td>Adams</td><td>234234</td><td>amy.adams@hotmail.com</td>   <td><a href="#" id="deleteEvent">Delete</a></td></tr>
            <tr id="drow"><td>Megan</td><td>Huffman</td><td>12255</td><td>amy.adams@hotmail.com</td><td><a href="#" id="deleteEvent">Delete</a></td></tr>
        </table>
        <a href="#" class="addRecord">Add Record</a> 
    </div>

您在 HTML 中重复使用id值,这是无效的。 鉴于此,选择这些id的任何行为都是不确定的。 例如:

$("#drow").remove();

它可能会删除第一个#drow,它可能会删除所有它们,它可能不删除它们,它可能会抛出错误等。 由于标记无效,因此行为未定义。

因此,您要做的第一件事是不要在 HTML 中重用id值。 您显示的 HTML 可以改用class值:

<tr class="drow">

或者,您可能根本不需要idclass...

如果删除按钮位于行内,则可以引用相对于单击的按钮的行:

$(this).closest('tr').remove();

这将从调用事件的元素开始,向上遍历 DOM,直到找到第一个tr元素,然后删除该元素。

<小时 />

编辑:您还在a标签上使用重复的id

<a href="#" id="deleteEvent">

您可以将它们替换为class

<a href="#" class="deleteEvent">

并将您的选择器更改为:

$(".deleteEvent").click(function(e) {
    // code
});

或者,您可以完全删除idclass,因为您仍然可以在没有它的情况下识别元素:

$("#students a").click(function(e) {
    // code
});

使用这个

<script type="text/javascript">
        $(function() {
            $("#deleteEvent").click(function(e) {
                $(this).parent('tr').remove();
            });
    </script>

请将您的函数替换为下面给出的函数。 它的工作。我已经检查过了。

$(function() {
    $("table a").click(function(e) {
        $(this).parent().parent().remove();
        return false;
    });
});