[英]Add removed element back to DOM jQuery 2
我有以下代碼,我想在其中刪除元素並將其添加回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的值不等於零時,我的元素.pm-container不會重新添加到我的頁面中。
知道為什么嗎?
謝謝你的幫助。
刪除元素后,它就消失了。 沒有辦法把它找回來。 一種解決方案是將元素克隆到變量中,並在以后可以重用:
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(); } } }); }
首先在ajax函數之外為您的Clone .pm-container
創建一個變量
注意*:使用.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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.