简体   繁体   English

将JS事件限制为每个用户每天一次

[英]Limit JS event to once per day per user

I am hoping to limit the event below to once a day per user. 我希望将以下事件限制为每位用户每天一次。 This will be a shadowbox that appears when the user tries to leave the page. 当用户尝试离开页面时,将出现一个阴影框。 I don't want to annoy the user with this every time their mouse leaves the body, so it should only happen the first time they are on the site each day. 我不想让用户每次鼠标离开身体时都会对此感到烦恼,因此应该只在他们每天第一次访问该网站时发生。

$('body').one('mouseleave', function() {
    $('.shadowbox').fadeIn(400)
});

I have been advised that using a cookie would be a good way to do this, but I am inexperienced in using cookies. 我被告知使用cookie是实现此目的的一种好方法,但是我对使用cookie经验不足。 Thank you! 谢谢!

You can set the cookie in that function with an expiry. 您可以在该函数中将Cookie设置为过期。

Good documentation is available on this here . 此处提供了很好的文档。

Basically, do a check and set in that function. 基本上,进行检查并设置该功能。

$('body').one('mouseleave', function() {
    var cookie = document.cookie; //You need to find the cookie you need here (if it exists, don't do anything)
    return; //if exists
    $('.shadowbox').fadeIn(400)
    document.cookie = "myCookieName=true; expires=(datetime + 1day)"
});

That way, you only get to fade and setting if there isn't a cookie available. 这样,只有没有cookie时,您才能淡入淡出并进行设置。

You can find infos about using cookies with javascript here : How do I create and read a value from cookie? 您可以在此处找到有关将cookie与javascript一起使用的信息: 如何创建cookie并从中读取值?

Then, assuming you're using the solution above : 然后,假设您使用的是上述解决方案:

$('body').on('mouseleave', function() {
    var cookie = getCookie('visited');
    if ('' == cookie) {
        $('.shadowbox').fadeIn(400);
        createCookie('visited', 'yes', 1);
    }
});

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

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