通过检查cookie动态更改jQuery“悬停”

Dynamically change jQuery "hover" by checking cookie

本文关键字:jQuery 悬停 检查 cookie 动态      更新时间:2023-09-26
如何

通过检查用户cookie来更改jQuery .hover()中的函数?

现在,代码在网站首次加载时有效,但是当cookie更新(通过javascript)时,除非重新加载页面,否则.hover()不会切换:

    var SkinChk = getCookie('skincookie');
    $('.fadeMenu').hover(function(){
        if (SkinChk == 'Alternative') {
            // Alternative Skin
            $(this).stop().animate({ backgroundColor:'rgb(66, 137,170)', color:'#F7F9F4'},500);
        } else {
            // Default Skin
            $(this).stop().animate({ backgroundColor:'rgb(255,165,0)', color:'#FFFFFF'},500);
        }
    }, function(){
        if (SkinChk == 'Alternative') {
            // Alternative Skin
            $(this).stop().animate({ backgroundColor:'rgb(247, 249, 244)', color:'#1F262A'},500);
        } else {
            // Default Skin
            $(this).stop().animate({ backgroundColor:'rgb(201,224,179)', color:'#333333'},500);
        }
    });

var SkinChk = getCookie('skincookie');引用了一个工作 javascript 函数,为了简洁起见,我没有发布。它返回 cookie 值。

好吧,你只检查一次cookie,所以没有什么可以告诉函数更新SkinChk变量。

解决此问题的最简单方法是在悬停功能内移动cookie检查:

var SkinChk;    
$('.fadeMenu').hover(function(){
    //Check if the cookie has changed
    SkinChk = getCookie('skincookie');
    if (SkinChk == 'Alternative') {
        // Alternative Skin
        $(this).stop().animate({ backgroundColor:'rgb(66, 137,170)', color:'#F7F9F4'},500);
    } else {
        // Default Skin
        $(this).stop().animate({ backgroundColor:'rgb(255,165,0)', color:'#FFFFFF'},500);
    }
}, function(){
    //Check if cookie has changed
    SkinChk = getCookie('skincookie');
    if (SkinChk == 'Alternative') {
        // Alternative Skin
        $(this).stop().animate({ backgroundColor:'rgb(247, 249, 244)', color:'#1F262A'},500);
    } else {
        // Default Skin
        $(this).stop().animate({ backgroundColor:'rgb(201,224,179)', color:'#333333'},500);
    }
});

您还可以创建一个事件来侦听监视 cookie 的服务。查看nsICookieService。不过,我不会推荐它,因为对于您要做的事情来说,这似乎是巨大的矫枉过正,但这是一种选择。

我认为如果不重新加载页面,您将无法获得更新的cookie。与其尝试在设置 cookie 之外单独检查 cookie,不如运行 javascript,使切换 WITH cookie 设置 javascript。