简体   繁体   English

Jquery.remove() 仅在第二次点击后起作用

[英]Jquery .remove() only acts on second click and after

I have a bootstrap popover that pops up after clicking on a notification icon on my page.单击页面上的通知图标后,我会弹出一个引导弹出窗口。 Part of its functionality is to remove any notification from the popover after clicking on it.它的部分功能是在单击弹出框后从弹出框中删除任何通知。 Here is an image of the popover with three notifications, for reference:这是带有三个通知的弹出窗口的图像,以供参考:

notifications通知

However, when I open the notification popover, then click on any of the notifications, the first click won't remove the notification, but the second one will.但是,当我打开通知弹出框,然后单击任何通知时,第一次单击不会删除通知,但第二次会删除。 The click listener is firing both the first and second times (confirmed with logging to console).点击监听器第一次和第二次触发(通过登录到控制台确认)。 I checked other questions similar to mine, but none of them had a solution that worked for me.我检查了与我类似的其他问题,但没有一个问题适合我。 I read up on something about the "focus" but couldn't understand what they meant.我读了一些关于“焦点”的东西,但不明白它们的意思。 Maybe that has something to do with it?也许这与它有关?

Here is the popover code:这是弹出框代码:

 $(document).ready(function(){ $("#notificationsBell").popover({ 'title': $('.notifications-title-header').html(), // display:none so it doesn't show up in window 'html': true, 'placement': 'left', 'content': $(".notifications-list").html() // display:none }); });

And here is the click listener that is supposed to remove the notification:这是应该删除通知的点击监听器:

 $('body').off("click").on("click", ".popover-body.notif-popup-container", function() { var notifId = $(this).attr("id"); $('#' + notifId).remove(); })

I think it has to do with the popover and display:none aspects.我认为这与 popover 和 display:none 方面有关。 This is because I try removing elements elsewhere in the code without display:none and the popover, and it works on the first click.这是因为我尝试在没有 display:none 和弹出框的情况下删除代码中其他地方的元素,并且它在第一次单击时起作用。 Any insight is appreciated!任何见解表示赞赏!

If the element you're adding a click event listener to.如果要向其添加单击事件侦听器的元素。 doesn't exist yet that could be a problem.尚不存在,这可能是个问题。

What's .off btw什么是.off顺便说一句

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

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