2016-04-04 23 views
0

我有三個按鈕,參數添加到我的網址 - 是這樣的:如何使用Cookie使用jQuery和自定義的URL參數

<a class="click1">/a> = ?param=grid 
<a class="click1">/a> = ?param=smallgrid 
<a class="click1">/a> = ?param=largegrid 

這些按鈕顯示了三種不同的佈局 - 第一個被設置爲默認值。

我想將用戶選擇放入cookie中 - 但我只需要將url添加到相關頁面。

的URL看起來是這樣的:

/products/Computers/Notebooks?param=list 

所以我想cookie來執行根據網址有/產品,甚至更好的選擇 - 體類,如果可能的。

我已將jquery.cookie.js插件添加到我的網站 - 但我無法弄清楚如何使用它。

回答

1

This SO answer顯示了JQuery Cookie庫的一個非常基本的用法。基本上用法是$.cookie(<cookie-key>, <cookie-value>, {<additional data about cookie>})。 (這顯然是僞代碼)。 這將向瀏覽器寫入一個鍵/值cookie,該cookie將持續您指定的時間,並可通過$.cookie("<cookie-key>")獲取並通過$.removeCookie("<cookie-key>")刪除。

因此,對於你的使用情況下,它可能是這樣的:

HTML 
<a id="gridbtn" class="click1"></a> 
<a id="smallgridbtn" class="click1"></a> 
<a id="largegridbtn" class="click1"></a> 

// JQuery 
$(document).ready(function() { 
    // After page load 
    var cookieLayoutValue = $.cookie("layout"); 

    console.log("The cookie value was " + cookieLayoutValue); 

    if (cookieLayoutValue === "grid") { 
     // process "grid" layout 
    } else if (cookieLayoutValue === "smallgrid") { 
     // process "smallgrid" layout 
    } else if (cookieLayoutValue === "largegrid") { 
     // process "largegrid" layout 
    } else { 
     // cookie doesn't exist, default it to grid 
     $.cookie("layout", "grid", { expires : 999 }); 
     // process "grid" layout 
    } 

    // 
    // call layout code for whatever the value is using if/else 
    // 

    // Wire up some click handlers 
    $("#gridbtn").click(function() { 
     var layout = $.cookie("layout"); 
     $.cookie("layout", "grid", { expires : 999 }); 

     // If the layout has changed 
     if (layout !== "grid") { 
      // Do "grid" layout processing 
     }    
    }); 

    // Wire up some click handlers 
    $("#smallgridbtn").click(function() { 
     var layout = $.cookie("layout"); 
     $.cookie("layout", "smallgrid", { expires : 999 }); 

     // If the layout has changed 
     if (layout !== "smallgrid") { 
      // Do "smallgrid" layout processing 
     }    
    }); 

    // Wire up some click handlers 
    $("#largegridbtn").click(function() { 
     var layout = $.cookie("layout"); 
     $.cookie("layout", "largegrid", { expires : 999 }); 

     // If the layout has changed 
     if (layout !== "largegrid") { 
      // Do "largegrid" layout processing 
     }    
    }); 
}); 

否則,你必須在cookie你想要的信息發送到服務器進行處理。我建議通過Spring Framework提供RESTful服務,然後在響應like this中設置cookie。

+0

嗨,謝謝。我確實遇到過這個帖子 - 但我仍然不明白如何爲我的特定需求編寫cookie。這很有趣,但有點難以掌握。 –

+0

添加了一個用例來幫助澄清 –

+0

嗯,這確實闡明瞭一點有趣。所以我基本上爲每個處理程序添加了我的佈局腳本。愚蠢的問題 - 我確實需要將它保存爲自己的.js,或者我可以將它用作普通腳本並將其添加到我現有的腳本文件中?再次感謝。 –

相關問題