JavaScript 动态删除 <tr> 表格行

标签 javascript php jquery html

我正在尝试从动态表中删除行。我已成功从 JavaScript 追加新行。

JavaScript

$(document).ready(function() {
    // table #pos add-row
    $(".add-row").keypress(function(e) {
        if (e.which == 13) {

            var barcode = $("#barcode").val();
            $.ajax({
                type: "post",
                url: "production/ajax/load.php",
                dataType: "json",
                data: {
                    barcode: $("#barcode").val()
                },
                success: function(data) {
                    $("#pos tbody").append(data['content']);
                }
            });
        }
    });

    // Find and remove selected table rows
    $(".delete-row").click(function(){
        alert('Success');
        $("#pos tbody tr").remove();
    });
})

load.php

    <?php
if (isset($_POST['barcode'])) {
    require '../controller/connection/connection-management.php';

    $barcode = $_POST['barcode'];
    $status = false;

    $sql = "SELECT code, title, wri_name, pub_name, year, main_category.main_category, category.category, call_number, pusat_penerbit, mrican, paingan, selling_price, discount FROM product, writer, publisher, main_category, category WHERE product.writer = writer.writer AND product.publisher = publisher.publisher AND product.main_category = main_category.main_category AND product.category = category.category AND code = '{$barcode}' ORDER BY title";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) == 1) {
        while($row = mysqli_fetch_assoc($result)) {
            $barcode = $row['code'];
            $title = $row['title'];
            $sellingPrice = number_format($row['selling_price'], 0, ',', '.');
            $quantity = 1;
            $discount = $row['discount'];
            $total =  number_format((($row['selling_price'] - ($row['selling_price'] * ($discount / 100))) * $quantity), 0, ',', '.');

            $append = "<tr class='pointer'>
                <td align='right'><a href='javascript:;' class='delete-row'><i class='fa fa-trash'></i></a></td>
                <td><small>{$barcode}</small></td>
                <td><div style='text-align: justify'><strong>{$title}</strong></div></td>
                <td align='right'>{$sellingPrice}</td>
                <td align='center'><input id='quantity' type='text' class='form-control' style='text-align:center' value='1'></td>
                <td align='center'><input type='text' class='form-control' style='text-align:center' value='{$discount}'></div></td>
                <td align='right'>{$total}</td></td>
            </tr>";
        }
        $status = true;
    }

    $data = array(
        "status" => $status,
        "content" => $append
    );

    echo json_encode($data);
}
?>

pos.php 这是 html 表格

<div class="x_title">
    <div class="input-group">
        <span class="input-group-btn">
        <button type="button" class="delete-row btn btn-primary"><i class="fa fa-pencil-square-o"></i></button>
    </span>
        <input name="barcode" id="barcode" type="text" class="add-row form-control" placeholder="Enter item name or scan barcode">
        <div class="input-group-btn">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Receive</button>
            <ul class="dropdown-menu dropdown-menu-right" role="menu">
                <li><a href="#">Receive</a></li>
                <li><a href="#">Return</a></li>
                <li><a href="#">Purchase Order</a></li>
                <li><a href="#">Transfer</a></li>
                <li><a href="#">Store Account Payment</a></li>
            </ul>
        </div>
    </div>
</div>

<div class="x_content">
    <div class="table-responsive">
        <table name="pos" id="pos" class="table table-striped jambo_table bulk_action">
            <thead>
                <tr class="headings">
                    <th style="text-align:center" class="column-title col-sm-7" colspan="3">Item Name </th>
                    <th style="text-align:right" class="column-title col-sm-1">Cost </th>
                    <th style="text-align:center" class="column-title col-sm-2">Qty. </th>
                    <th style="text-align:center" class="column-title col-sm-1">Disc % </th>
                    <th class="column-title col-sm-1" style="text-align:right">Total </th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </div>
</div>

因此,当我在表中添加新行时,一切正常,如下图所示:

#pos tbody append

但是当我单击带有 class='delete-row' 的垃圾桶图标时,这不起作用。所以我认为,当我将数据附加到表 tbody 时,它不会从新行中读取类或 id。

请有人帮忙。我找不到像我这样的类似问题。我只是想知道,当我点击 JavaScript 中的垃圾桶图标时如何删除表格行。

最佳答案

您这里有两个问题(这就是为什么我没有投票关闭作为重复项)。首先,您需要在 .delete-row 元素上使用委托(delegate)事件处理程序,因为它会在加载后附加到 DOM。当您尝试在元素存在之前附加事件处理程序时,您当前的代码不会执行任何操作。

其次,您需要使用 DOM 遍历删除被单击按钮的父 tr。目前,您的代码将删除所有行。试试这个:

$('#pos').on('click', '.delete-row', function() {
    $(this).closest('tr').remove();
});

关于JavaScript 动态删除 <tr> 表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44040804/

相关文章:

php - 使用 php 和 Mysql 跟踪数据库使用情况

javascript - ng-bootstrap datepicker 无法在选择之前设置默认日期

javascript - jQuery 元素大小调整在实时站点上不起作用,在本地版本上起作用。 Chrome

php - Codeigniter:将额外参数插入到 MySQL 语句中

php - Codeigniter 更新批量查询问题

Javascript - 当输入中有内容时按钮可见

javascript - 跟踪滚动事件的页码

javascript - jQuery 自定义 Accordion ,无法使其可折叠

javascript - 如何应用所有类名值? JS

javascript - Django 中非常非常基本的 JavaScript 按钮