1)使用jQuery cookie庫以方便使用。 https://github.com/carhartl/jquery-cookie
2)檢查cookie存在並處理相應
if ($j.cookie("NameOfYourCookie") == null) {
//Do stuff if cookie doesn't exist like set a cookie with a value of 1
$j.cookie("NameOfYourCookie", 1, {expires: 10, path:'/'});
}
else {
//They have a cookie so do something
alert ('You have a cookie with name NameOfYourCookie');
}
*編輯*
想我可以編輯我的答案是更適合您的問題。
<button class="yes">YES</button>
<button class="no">No</button>
var $j = jQuery.noConflict();
$j(document).ready(function(){
//Show modal on page load
$j("#myModal").show();
$j('.yes').click(function(){
$j("#myModal").hide();
$j.cookie("YesButtonCookie", 1, {expires: 10, path:'/'});
alert ('You have clicked yes, a cookie has been dropped');
});
if ($j.cookie("YesButtonCookie") == 1){
// Don't show the div
$j("#myModal").hide();
alert ('Cookie found, you cant see myModal');
}
if ($j.cookie("YesButtonCookie") == null){
// Cookie Not Found
alert ('Cookie Not found, you can see myModal');
$j("#myModal").show();
}
$j('.clearcookie').click(function(){
$j.cookie("YesButtonCookie", null);
alert('Cookie Cleared');
});
});
JSFIDDLE TO TEST
哇,這就是我所說的一個詳細的解答!我遇到了一些問題,當我訪問Firefox中的JSFiddle頁面時,它警告我發現了cookie,所以我嘗試了清除按鈕並刷新頁面,但仍然找到cookie。所以我嘗試在IE瀏覽器,並沒有找到cookie(點擊「是」按鈕後),然後刷新。我是否錯過了一些東西,或者這個工作不正常嗎? – Greg 2013-04-05 15:12:14
我可能沒有正確清除小提琴中的cookie或未正確調用它。基本的輪廓在那裏。使用jQuery cookie插件,然後使用$ j.cookie(「CookieName」,IntValue,{expires:IntDaysToExpire,path:'/'})設置cookie。檢查cookie是否加載檢查您分配的值。在我的示例中,我將值設置爲1,以便在($ j.cookie(「CookieName」)== 1){// do stuff}的情況下檢查cookie是否具有值1。一旦你能夠設置/讀取cookies,那麼你想要做的所有事情都屬於if語句的組合。希望能幫助到你。 – James 2013-04-08 03:53:28
太棒了,再次感謝您的幫助James!你是冠軍 – Greg 2013-04-08 14:41:08