javascript - 使用 jquery 单击按钮时如何删除特定行?

标签 javascript php jquery mysqli

我有一个玩家数据表,每行旁边都有一个删除按钮。 单击该按钮时,应该使用 jQuery 立即删除该特定行。到目前为止我已经包含了我的代码。当应该单击按钮时我真的被卡住了。我应该使用 header 函数吗?

index.php

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css"></link>
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/script.js"></script>
    </head>
<body>
    <!-- Create a table-->
    <table style width="800" border="1" cellpadding="1" cellspacing="1"> 
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <tr>
    <th>Player ID</th>
    <th>Player Name</th>
    <th>Player Position</th>
    <th>Delete</th>
    </tr>

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "<div class = 'row'>";
            echo "<tr>";
            echo "<td>".$row['id']."</td>";
            echo "<td>".$row['surname']."</td>";
            echo "<td>".$row['position']."</td>";
            echo "<td><button id = 'dlt_btn' type='button'>Delete</button></td>";
            echo "</tr>";
            echo "</div>";


        }



    ?>

</body>

script.js

$(document).ready(function () { 

    $("#dlt_btn").click(function(){
        //Activate 'delete.php'
    });

});

删除.php

?

最佳答案

在此上下文中,您应该使用类与 ID,但您可以使用 $(this) 来定位单击的元素,并通过 .parent() jquery 方法遍历/删除。这纯粹是为了从 DOM 中删除行,您需要执行 ajax 请求来告诉服务器要从数据库中删除哪一行。在这种情况下,您应该将行 ID 属性添加到 html 中,并将其与 AJAX 请求一起发送。

您可以将行 ID 作为属性附加到按钮中,例如

<button id = 'dlt_btn' type='button' row-id='<?=$yourRowID%>'>Delete</button>

$(document).ready(function () { 

    $("#dlt_btn").click(function(){
        let rowId = $(this).attr('row-id'); //Pull the attribute from your button
        let tr =  $(this).parent().parent(); //Define the TR itself

        $.post('/delete.php', {row_id:  rowId}, function(result){
          //Do something with the message your page returns after deleting
          tr.remove(); //Remove the TR from the dom
        });
    });

});

关于javascript - 使用 jquery 单击按钮时如何删除特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44376349/

相关文章:

javascript - TypeError : (intermediate value). 那么不是一个函数

php - 无法登录 Php MySQL android

javascript - 如何在 React Native 中截图测试?

php - 碳/日期时间 : The timezone could not be found in the database

php - MySQL-替换整个表中所有行和列的空间

jquery - map 缩放和选择 JQuery 插件?

javascript - 在 jquery 中选项卡可见后执行某些操作

jquery 处理程序无法使用动态添加的 id

javascript - HTML 图像的相对路径。在 Github 页面上找不到 404

JavaScript 错误 : "val.match is not a function"