0

我有以下代码,我想在 jQuery 中删除元素并将其添加回 DOM:

var pm_container = $(document).find('.pm-container');

$(document).on('change', '#payment-form .cat_field', function(){
    displayPrice($(this), pm_container);
});

function displayPrice(elem, pm_container){
    $.ajax({
        type: 'GET',
        url: 'getamount.php',
        dataType: 'json',
        cache: false,
        success: function (data) {
            var amount_field = $(document).find('#payment-form #amount');

            amount_field.val(data.price);

            if(amount_field.val() == 0) {
                $(document).find('.pm-container').remove();
            } else {
                $(document).find('.save-listing').prev(pm_container);
            }
        }
    });
}

出于某种原因,当amount_field的值不等于 0 时,我的元素.pm-container不会重新添加到我的页面中。

知道为什么吗?

谢谢你的帮助。

4

2 回答 2

0

当您删除元素时,它就消失了。没有办法取回它。一种解决方案是将元素克隆到变量中,以便以后重新使用它:

var pm_container = $(document).find('.pm-container').clone();

$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });

function displayPrice(elem, pm_container){
$.ajax({
    type: 'GET',
    url: 'getamount.php',
    dataType: 'json',
    cache: false,
    success: function (data) {
        var amount_field = $(document).find('#payment-form #amount');

        amount_field.val(data.price);

        if(amount_field.val() == 0) {
            $(document).find('.pm-container').remove();
        } else {
            $(document).find('.save-listing').prepend(pm_container);
        }
    }
}); }

但是,对于您的情况,最好的方法可能是隐藏并显示元素:

$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });

function displayPrice(elem){
$.ajax({
    type: 'GET',
    url: 'getamount.php',
    dataType: 'json',
    cache: false,
    success: function (data) {
        var amount_field = $(document).find('#payment-form #amount');

        amount_field.val(data.price);

        if(amount_field.val() == 0) {
            $(document).find('.pm-container').hide();
        } else {
            $(document).find('. pm-container').show();
        }
    }
}); }
于 2018-09-08T06:43:49.630 回答
0

.pm-container首先为您的 Clone outside ajax 函数创建一个变量

注意*:当您使用 .remove() 时,您无法将其取回。

var container = $(".pm-container").clone();

然后在你的ajax函数里面

if (amount_field.val() == 0) {
  $(".pm-container").detach();
} else {
  container.insertBefore($(".save-listing"));
}

jsfiddle:https ://jsfiddle.net/marksalvania/3h7eLgp1/

于 2018-09-08T12:37:03.140 回答