【问题标题】:How do I use jQuery Cookie plugin to create a cookie that updates without page refresh?如何使用 jQuery Cookie 插件创建无需刷新页面即可更新的 cookie?
【发布时间】:2012-09-10 15:40:29
【问题描述】:

我正在记录用户在查看页面时单击的类/id/文本。无论如何,下面的代码有效(cookie 值除外)...

// JavaScript Document
$(document).ready(function() {

    $("div,input,a,select,option,button,img,td",this).click(function(){

        var clickedText = $(this).text().substring(0, 30);

        // Get Element Values
        var elementClass = $(this).attr('class');                       
        var elementID = $(this).attr('id');

        // If element has no class then set var to ""
        if (typeof elementClass !== 'undefined' && elementClass !== false) {
            var elementClass = " " + elementClass;
        } else {
            var elementClass = "";
        }

        // If element has no class then set var to ""
        if (typeof elementID !== 'undefined' && elementID !== false) {
            var elementID = " / " + elementID + " |";
        } else {
            var elementID = "";
        }

        // Create string
        var clickedCookie = elementClass + elementID;

        // Print output on delevopment
        $("#show-cookies").append(clickedCookie + clickedText);

        // Set Cookie
        $.cookie('lastClicked', clickedText);

    });
});

我有 jQuery cookie 插件,目前在各种其他 jQuery 脚本中使用它。通过上面的操作,创建了一个 cookie,但它的值类似于“0A%09%20%0A%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%0A%09”。我的代码中有什么东西会创建一个奇怪的 cookie 值吗?

应该和$("#show-cookies").append(clickedCookie + clickedText); 的输出类似吧?

像我想要的那样输出la3down | / lc-btn | / live-chat-contain | / live-chat | / contentWide | / frame-wrap

基本上,我需要像上面那样读取 cookie 的值。有没有人有任何使用 jQuery Cookie 插件的经验? https://github.com/carhartl/jquery-cookie/我做错了吗?

最终,每次单击元素时我都需要更新 cookie 值...这意味着我还需要 .append() cookie 值(我认为?)。仍在研究 _gaq.push 命令...指向这将是一个额外的奖励哈哈...

【问题讨论】:

    标签: jquery jquery-plugins cookies


    【解决方案1】:

    我已经为上述问题完成了完整的垃圾箱。这里也是演示链接...

    演示: http://codebins.com/bin/4ldqp7i

    HTML

     <span>
      <div id="show-cookie" class="cookie">
      </div>
    </span>
    <span>
      <button id="btnread" class="btnclass">
        Read Cookie
      </button>
      <button id="btnreset" class="btnclass">
        Reset Cookie
      </button>
    </span>
    <span>
      <div class="divblock">
        Div-Text
      </div>
    </span>
    <span>
      <input type="text" class="input" size="15" value="InputValue" id="txtinput"/>
    </span>
    <span>
      <a href="#" id="aLink" class="linkclass">
        My Text Link 
      </a>
    </span>
    <span>
      <select id="select_tag" class="selclass">
        <option>
          Option-1
        </option>
        <option>
          Option-2
        </option>
        <option>
          Option-3
        </option>
        <option>
          Option-4
        </option>
      </select>
    </span>
    <span>
      <img src="http://profile.ak.fbcdn.net/hprofile-ak-prn1/50305_151863314933391_163751676_q.jpg" id="img1" class="imgclass" />
    </span>
    <span>
      <table class="table" cellspacing="1" cellpadding="1">
        <tr>
          <td class="cell1" id="td1">
            Cell-1
          </td>
          <td class="cell2" id="td2">
            Cell-2
          </td>
          <td class="cell3" id="td3">
            Cell-3
          </td>
        </tr>
      </table>
    </span>
    
    <span>
      <input type="button" id="btn1" class="btnclass" value="Submit" />
    </span>
    

    jQuery

        $(function() {
    
        $("div,input,a,select,option,button,img,td").not(':button[id=btnread],:button[id=btnreset]').click(function() {
            var clickedText = "";
            if (typeof $(this).attr('value') != 'undefined') {
                clickedText = $(this).attr('value').trim().substring(0, 30);
            } else {
    
                clickedText = $(this).text().substring(0, 30);
    
            }
    
            var elementClass = " ";
            var elementID = "";
            if (typeof $(this).attr('class') != 'undefined') {
                if ($(this).attr('class').trim() != "") elementClass += $(this).attr('class').trim();
            }
    
            if (typeof $(this).attr('id') != 'undefined') {
                if ($(this).attr('id').trim() != "") elementID += " / " + $(this).attr('id').trim() + " |";
            } else {
                elementClass += " |";
            }
            // Create string
            var clickedCookie = elementClass.toString() + elementID.toString();
    
            // Print output on delevopment
            $("#show-cookie").append(clickedCookie + clickedText);
            //Check Existing Cookie 
            var ckVal = ($.cookie('lastClicked'));
            if (ckVal != 'undefined' || ckVal != null) {
                ckVal += " " + clickedText;
            } else {
                ckVal = clickedText;
            }
    
            // Set Cookie
            $.cookie('lastClicked', ckVal, {
                expires: 2,
                path: "/"
            });
            $("#show-cookie").show(500);
        });
    
        $("#btnread").click(function() {
            var ck = ($.cookie('lastClicked'));
            alert(ck);
        });
        $("#btnreset").click(function() {
            $.cookie('lastClicked', "");
            $("#show-cookie").html("").hide(400);
        });
    });
    

    CSS:

    span {
      display:block;
      margin-top:5px;
    }
    .divblock {
      background:#94dca8;
      color:#333;
      width:300px;
      text-align:center;
    }
    .input {
      border:1px solid #335599;
      color:#335599;
    }
    .selclass {
      border:1px solid #1122a9;
      color:#1122a9;
      background:#94dca8;
    }
    .imgclass {
      border:1px solid #1122a9;
    }
    .table {
      width:50%;
      border:1px solid #2255dc;
    }
    td {
      text-align:center;
    }
    .cell1 {
      background:#caa8a9;
    }
    .cell2 {
      background:#a8b8ed;
    }
    .cell3 {
      background:#a8bfac;
    }
    .btnclass {
      border:1px solid #333;
      background:#ada5a4;
    }
    .btnclass:hover{
      background:#cdcaca;
    }
    .cookie{
      background:#fda5b7;
      border:1px solid #fa6289;
      display:none;
    }
    

    演示: http://codebins.com/bin/4ldqp7i

    【讨论】:

    • 今天要玩这个。感谢您的详细回复。这看起来很棒!甚至使用了我的选择器 :) 谢谢!
    • 这在 codebin 上效果很好,但是当我把它带到我们的服务器时,没有骰子?我错过了什么吗?我们在 Windows Server 2003 上运行 IIS...http://www.horsepowerfreaks.com/js/clickedcookie/demo.html
    • 在您给定的 URL 中,js 目录受到限制,因此我无法访问,但请检查您的 head 标签中是否包含最新的 jquery.js 和 jquery.cookie.js 以及有效文件网址/路径...?
    【解决方案2】:

    因为 cookie 在 http 请求中来回传输,所以它们会得到 url-encoded,因此 cookie 原始值可能会与其原始值不同。下面是一个例子:

    原值:

    2012 年 9 月 9 日,星期日

    编码值:

    星期日%2C+09+九月+2012

    使用 jQuery cookie 插件时,您不必担心这一点,因为它会为您处理编码/解码。但是,如果您尝试在服务器端读取 cookie 值,则可能需要对其进行解码。请查看this SO Question 了解更多信息。

    【讨论】:

    • 糟糕的是我正在使用cookie插件...我想知道为什么它没有被解码? @Thomas C. G. de Vilhena
    【解决方案3】:

    我知道你要去哪里,但是$("div,input,a,select,option,button,img,td",this).click(function(){ 将点击绑定到你选择的每个元素,包括那些嵌套元素。因此,您可能会在每次用户点击时获得多个值,不确定这是否是您所需要的。

    关于您的问题,cookie 是 url 编码的,您可以通过decodeURIComponent(clickedText) 获取解码后的文本。下次如果迷路了,用console.log追查问题,很多。

    【讨论】:

    • 我想知道为什么它给了我 4-5 个不同的类/ID 哈哈。是,this 造成的吗?我假设它会在最前面的元素上注册 .click() 。我想这是有道理的,它会回火倍数。关于如何防止这种情况的任何建议?今晚将尝试 decodeURIComponent()。感谢您的提示:)
    猜你喜欢
    • 2015-12-08
    • 2012-04-06
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 2015-07-24
    • 2013-05-28
    • 2012-12-28
    • 2011-03-22
    相关资源
    最近更新 更多