繁体   English   中英

如何在不刷新页面的情况下从DOM中删除prepend / append元素

[英]How to remove the prepend / append element from the DOM without page refresh

我正在使用bootstrap popover,我想向DOM中添加某些元素。 我使用以下命令在标题中添加了一个附加元素:

$('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
$('.main-header-title').append('<span class="close" id="cross-button">&times;</span>');

但是,如果我不刷新页面,则('div.popover')会始终在<h3>元素之前,并且我在弹出窗口中看到重复的标题。 类似于下面的屏幕截图:

在此处输入图片说明

谁能帮助我将元素设置为null,以便当我再次搜索(不刷新)时,它不会显示重复的标题名称。

谢谢!

您只能使用DOM中尚不存在的内容进行追加

if ($('h3.main-header-title').length==0) {
     $('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
     $('.main-header-title').append('<span class="close" id="cross-button">&times;</span>');
}

您只能使用javascript来实现此目的

var element =  document.getElementsByClassName("main-header-title");
if (element.length ==0)
{
 $('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
         $('.main-header-title').append('<span class="close" id="cross-button">&times;</span>');
}

或者,您也可以在将它们添加到DOM后的一段时间(例如1秒)后将其删除

setTimeout(function(){
$("h3.main-header-title").remove();
// or $("h3.main-header-title").fadeOut(100); for animated removal
},1000);

为了获得更好的用户体验,如果要重新显示弹出窗口,请按照这种方式进行操作。

if ($('h3.main-header-title').length==0) {
         $('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
         $('.main-header-title').append('<span class="close" id="cross-button">&times;</span>');
    }
else {
         $(h3.main-header-title).fadeOut(200);
         setTimeout(function(){$(h3.main-header-title).fadeIn(200);},500)
}

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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