我编写了下面的代码,在 5 秒后删除带有 rc-anchor-pt 类的元素(如果它存在于 DOM 中),
checkContainer();
counter = 1;
function checkContainer () {
alert("checkContainer");
$('.rc-anchor-pt').remove();
$('.rc-anchor-logo-portrait').append('<a href=\"http://www.un.org/en/aboutun/privacy/\" target=\"_blank\">Privacy & Terms</a>');
if($('.rc-anchor-pt').is(':visible')){ //if the container is visible on the page
var privacy = $('.rc-anchor-pt').find('a');
} else {
if (counter === 1)
{
setTimeout(checkContainer, 5000); //wait 50000 ms, then try again
counter++;
}
}
}
但是下面的行并没有从 DOM 中删除该元素。您能告诉我原因是什么吗?预先感谢。我正在 document.ready 内运行该元素仅存在于页面中 -
$('.rc-anchor-pt').remove();
最佳答案
我不太确定你想用你的代码来完成什么。您在问题中声明您希望在 5 秒后从 DOM 中删除一个元素...您应该能够使用以下代码来完成此操作:
$('.rc-anchor-logo-portrait').append('<br><a href=\"http://www.un.org/en/aboutun/privacy/\" target=\"_blank\">Privacy & Terms</a>');
setTimeout(function(){
$('.rc-anchor-pt').remove();
}, 5000);
按照您的代码布局方式,rc-anchor-pt
类将永远可见。那样的话就真的没有任何目的了。如果您希望 append
函数也在 5 秒后运行,只需将其放入 setTimeout 函数中即可。
这是一个 fiddle :https://jsfiddle.net/1399u65t/3/
关于javascript - Dom 操作不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40246214/