单击锚点时如何设置/存储 cookie [英] How can I set/store cookie when anchor clicked

查看:21
本文介绍了单击锚点时如何设置/存储 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Cookie,以便参考点击的锚标记应用默认样式或特定样式,即使浏览器关闭/重新打开也是如此.因此,如果用户单击第二个链接,关闭或刷新浏览器并重新打开,则样式仍应处于活动状态,如果这是他们第一次应用默认值.这有点超出我的地盘.

I am trying to use Cookie so that a default style OR a specific style is applied in reference to the anchor tag clicked, even when the browser is closed/reopen. So if the user clicked the second link, close or refresh the browser and reopen, than the style should still be active, if it is their first time the default should apply. This is a little over my turf.

这是 HTML:

<a id="default" href="#/">Default Style</a>
<a id="style2"  href="#/">Style 2</a>
<a id="style3"  href="#/">Style 3</a>

<ol>
<li><span>Hello World</span></li>
</ol>

JQuery:(对 StackOverflow 的赞美)

<script type="text/javascript">
$('#default').on('click',function(){
    $('ol li span').removeClass(function() {
          return $(this).attr('class');
        }).addClass('default');
});
$('#style2').click(function(){
    $('ol li span').removeClass(function() {
          return $(this).attr('class');
        }).addClass('style2');
});
$('#style3').click(function(){
    $('ol li span').removeClass(function() {
          return $(this).attr('class');
        }).addClass('style3');
});
</script>

CSS:

<style type="text/css">
.default{
color: #333;
}

.style2{
color: #999;
}

.style3{
color: #800;
}
</style>

推荐答案

有一个 jQuery cookie 插件可以用来设置和获取 cookie,但是如果 IE8 之前的浏览器不是问题,我会去改为使用本地存储,仅对使用旧版浏览器的 1% 访问者使用默认样式.

There is a cookie plugin for jQuery you can use to set and get cookies, but if browsers older than IE8 are'nt an issue, I'd go for local storage instead and just use the default style for the 1% of visitors using older browsers.

如果您向链接添加一个类,您可以在一个函数中定位所有这些类,只需根据点击的 ID 设置类,以下是使用本地存储的示例:

If you add a class to your links, you can target all of them in one function, and just set the class based on the ID clicked, here's an example using local storage:

$(function() {
    if (localStorage.getItem('style')) {
        $('ol li span').addClass(localStorage.getItem('style'));
    }else{
        $('ol li span').addClass('default');
    }

    $('.styles').on('click', function(e) {
        e.preventDefault();
        var styles    = ['default', 'style2', 'style3'],
            currStyle = this.id;

        $('ol li span').removeClass(styles.join(' ')).addClass(currStyle);

        localStorage.setItem('style', currStyle);
    });
});
​

FIDDLE

这篇关于单击锚点时如何设置/存储 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆