首页 > 解决方案 > jQuery:隐藏表格行

问题描述

这是按下按钮删除时调用的函数。确认删除后,我想隐藏删除 tr :

function delete_confirmation(id) {
    var $tr = $(this).closest('tr');
    swal({
        title: "Are you sure?",
        text: "To delete this patient!",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    })
    .then((willDelete) => {
        if (willDelete) {
            $.ajax({
                url: localStorage.getItem("base_url") + '' + 'index.php/Patient_ws/delete/',
                timeout: 4000,
                type: "POST",
                data: ({id: id}),
            }).done(function () {
                $tr.remove();
            })
            .fail(function () {
                swal({
                    title: ' erreur in server, try later...',
                    type: 'warning'
                })
            })
        } else {
            swal("Patient not deleted");
        }
    });
}

html标记:

<a href="#" class="btn btn-danger btn-xs" onclick="delete_confirmation(<?php echo $patient->id_personne;?>)">
<i class="fa fa-trash-o"></i> Delete </a>

我想隐藏 tr - 请帮忙。

标签: phpjqueryajaxcodeigniter

解决方案


除非您从 html 中传入,否则函数this中没有显式。onclick尝试console.log(this)会看到它可能Window不是元素

由于您已经在使用 jQuery,我建议您也将它用于事件侦听器并将 php 输出移动到数据属性

HTML

<a class="delete-row-btn btn btn-danger btn-xs" 
   data-id="<?php echo $patient->id_personne;?>">

JS

$(document).on('click','.delete-row-btn', delete_confirmation)

function delete_confirmation(event) {    
        event.preventDefault();
        // now `this` is the button
        var id = $(this).data('id')
        var $tr = $(this).closest('tr');
        // all else should be same
        swal({
              .....

}

推荐阅读