[英]How to remove the prepend / append element from the DOM without page refresh
I am using the bootstrap popover and i wanted to add certain elements to the DOM. 我正在使用bootstrap popover,我想向DOM中添加某些元素。 I am adding an additional element to the title using:
我使用以下命令在标题中添加了一个附加元素:
$('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
$('.main-header-title').append('<span class="close" id="cross-button">×</span>');
However if i dont refresh the page, the ('div.popover')
keeps prepending the <h3>
element and i have duplicate titles seen in the popover. 但是,如果我不刷新页面,则
('div.popover')
会始终在<h3>
元素之前,并且我在弹出窗口中看到重复的标题。 something like screenshot below: 类似于下面的屏幕截图:
Can anyone help me in setting the element to null, so that when i search again ( w/o refresh), it wont show me duplicate title names. 谁能帮助我将元素设置为null,以便当我再次搜索(不刷新)时,它不会显示重复的标题名称。
Thanks! 谢谢!
You can only append when its not already present in the DOM using 您只能使用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">×</span>');
}
You can achieve this using javascript only by 您只能使用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">×</span>');
}
Or you can remove them after some time (say 1sec) when they are added to DOM 或者,您也可以在将它们添加到DOM后的一段时间(例如1秒)后将其删除
setTimeout(function(){
$("h3.main-header-title").remove();
// or $("h3.main-header-title").fadeOut(100); for animated removal
},1000);
And for better UX if you want to re-display the popover, do it this way. 为了获得更好的用户体验,如果要重新显示弹出窗口,请按照这种方式进行操作。
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">×</span>');
}
else {
$(h3.main-header-title).fadeOut(200);
setTimeout(function(){$(h3.main-header-title).fadeIn(200);},500)
}
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.