gpt4 book ai didi

javascript - 如何在不刷新页面的情况下从 DOM 中删除前置/附加元素

转载 作者:太空宇宙 更新时间:2023-11-04 12:45:10 25 4
gpt4 key购买 nike

我正在使用 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> 前面加上元素和我在弹出窗口中看到重复的标题。类似于下面的截图:

enter image description here

任何人都可以帮我将元素设置为 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)
}

希望这对您有所帮助!

关于javascript - 如何在不刷新页面的情况下从 DOM 中删除前置/附加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26566003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com