gpt4 book ai didi

jquery - 如何检测 div 是否仍在 DOM 中

转载 作者:行者123 更新时间:2023-12-01 01:24:54 25 4
gpt4 key购买 nike

我想知道 DOM 中是否存在 div。我在网站上有一个通知,位于页面的最顶部,用户可以单击它,它会向上滑动。我有另一个 jquery 事件,该事件取决于知道这个 div 是否仍然存在于 DOM 中。我想要一个简单的脚本,它将生成一个 bool 值,指示该 Div 是否存在。我试过了

if($('#cookies_notification').css('display','block'))

这似乎承认 div 是否存在,但我还需要知道它是否不存在,我尝试使用“else”但没有运气。

那么检查 DOM 中是否存在元素的最佳方法是什么?

更新好吧,我错了,我认为它不会将 DOM 留在 slipUp 上,所以我需要知道元素上的 sliedUp 是否发生了。

更新2我想我可以在通知向上滚动时将 $('#cookies_notification').css('display','none') 添加到单击事件,然后它会检测到它。这是我能想到的唯一解决方案。

更新3哦,添加css代码就可以去除上滑效果了。

$("#cookies_notification").click(function(){
$(this).slideUp().css('display','none');

});

如何让它向上滑动然后改变显示方式?

最佳答案

如果您的选择器返回 0 个元素,则无法在 DOM 中找到它。

if( $('#cookies_notification').length === 0 ) {
// Do something
}

这是一个工作示例:http://jsfiddle.net/LT7g8/

或者,请参阅这个问题: Is there an “exists” function for jQuery?

如果您只是想知道该对象是否被隐藏(并且并非完全不存在于 DOM 中),请查看 jQuery :hidden selector 。如果该元素存在但已被隐藏,则此选择器将返回该元素。如果元素不存在,或者存在且可见,则不会选择该元素。

对于您的情况,听起来您想首先检测该元素是否存在,然后检测它是否已被 SlideUp() 隐藏。

var objCookieNotification = $('#cookies_notification');
if ( objCookieNotification.length === 0 ) {
// Notification does not exist in the DOM.
// Add it to the DOM here.
} else if ( objCookieNotification.is(':hidden') ) {
// Notification exists in the DOM but is hidden.
// Make it visible again here.
} else {
// The notification exists in the DOM and is already visible.
// If you need to make it flash or something, you can do that here.
}

关于jquery - 如何检测 div 是否仍在 DOM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16471513/

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