简体   繁体   中英

jQuery detach and appendTo multiple times

I want to detach a row when user clicked to a specific button inside row and append it to another table again and again.

My below script detaches and appends the other row once. However it continues toggling classes on following clicks, it doesn't make detach and append. It also cannot update the db.

What is wrong with this snippet?

$('.orderHideBtn').on('click',function(){
    var $oid = $(this).attr('id').split('-');
    $data = 'a=hideOrder&oid='+$oid[1];
    $.ajax({
        data: $data,
        success: function(msg){
            $('#hbtn-'+$oid[1]).toggleClass("orderHideBtn orderShowBtn").toggleClass('icon-eye-close icon-eye-open').closest('tr').detach().appendTo('#ordersTBody2');
            console.log('#hbtn-'+$oid[1]);
        }
    });
});
$('.orderShowBtn').on('click',function(){
    var $oid = $(this).attr('id').split('-');
    $data = 'a=showOrder&oid='+$oid[1];
    $.ajax({
        data: $data,
        success: function(msg){
            $('#hbtn-'+$oid[1]).toggleClass("orderShowBtn orderHideBtn").toggleClass('icon-eye-open icon-eye-close').closest('tr').detach().appendTo('#ordersTBody1');
            console.log('#hbtn-'+$oid[1]);
        }
    });
});

These are HTML buttons:

<span id="hbtn-{$o.orderID}" class="orderHideBtn icon-eye-close"></span>

and

<span id="hbtn-{$o.orderID}" class="orderShowBtn icon-eye-open"></span>

As you are switching class and selector relative to hanlder is not re-evaluated, you should delegate event, eg:

$(document.body).on('click','.orderHideBtn',function(){
    var $oid = this.id.split('-');
    $data = 'a=hideOrder&oid='+$oid[1];
    $.ajax({
        data: $data,
        success: function(msg){
            $('#hbtn-'+$oid[1]).toggleClass("orderHideBtn orderShowBtn").toggleClass('icon-eye-close icon-eye-open').closest('tr').appendTo('#ordersTBody2');
            console.log('#hbtn-'+$oid[1]);
        }
    });
});

I removed detach() method because, as i'm aware of, it is useless here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM