为最后五个点击链接设置cookie并获取该cookie

时间:2013-12-19 05:14:03

标签: php cookies

如果我有一个包含多个此类链接的网页

<a href="link_one">link one</a>
<a href="link_two">link two</a>
<a href="link_three">link three</a>
<a href="link_four">link four</a>
<a href="link_five">link five</a>
<a href="link_six">link six</a>

如果用户点击此链接,我想仅为最后五个点击的链接设置cookie,以及如何使用php获取该cookie

2 个答案:

答案 0 :(得分:0)

首先将代码设置为..

function SetCookie(COOKIENAME,value,expiredays)
    {
        var exdate=new Date()
        exdate.setDate(exdate.getDate()+expiredays)
        document.cookie=COOKIENAME+ "=" +escape(value)+
        ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
    }

然后提供链接详情

<a href="#" onClick="SetCookie('COOKIENAME','COOKIEVALUE','1')">
<a href="#" onClick="SetCookie('COOKIENAME','COOKIEVALUE','2')">
<a href="#" onClick="SetCookie('COOKIENAME','COOKIEVALUE','3')">
<a href="#" onClick="SetCookie('COOKIENAME','COOKIEVALUE','4')">
<a href="#" onClick="SetCookie('COOKIENAME','COOKIEVALUE','5')">

答案 1 :(得分:0)

你需要使用jquery cookie。 https://github.com/carhartl/jquery-cookie

<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<div class="set-cookie">
    <a href="link_one">link one</a>
    <a href="link_two">link two</a>
    <a href="link_three">link three</a>
    <a href="link_four">link four</a>
    <a href="link_five">link five</a>
    <a href="link_six">link six</a>
</div>
<script>
    $(document).ready(function () {
        var cookie = $.cookie('last_five_links');
        var links = null;
        if (typeof cookie == 'undefined')
            links = [];
        else
            links = cookie.split(',');


        $('.set-cookie a').click(function (e) {
            addLink($(this).attr('href'), links);
        });
    });

    function addLink(link, links) {
        if (links.length == 5) {
            links.shift();//remove the first link
        }
        links.push(link);
        $.cookie('last_five_links', links);
    }
</script>