2011-07-06 38 views
0

我正在使用從本網站上的帖子拼湊在一起的切換列表顯示。他們工作得很好,但我希望他們能夠保存一個cookie值。jQuery在使用「this」的切換列表中保存Cookie

我已經想出瞭如何在定位單個類/項目(例如「if(myCookie == value){do stuff to」.myClass「...}」)時使用Cookie。但問題在於我使用的是一組使用「$(this)」調用它們的列表。因此,通過類值定位它們將不起作用,因爲它們將使用該類定位所有內容。合理? Cookie需要實現「this」而不是「myClass」。

下面是我爲我的列表拼湊在一起的代碼。

// append links to the element directly preceding the element with a class of "toggle" 
$(".toggle").prev(".toggleList").append('<a href="#" class="toggleLink" id="collapse"></a>'); 

// hide all of the elements with a class of 'toggle' 
$('.toggle').show(); 

$('a.toggleLink').click(function() { 

    // change the link depending on whether the element is shown or hidden 
    if (!$(this).is('.active')) { 
     $(this).addClass('active'); 
     $(this).attr("id" ,"expand"); 
        THIS IS WHERE I NEED THE $.COOKIE TO WORK. I NEED IT TO REMEMBER THAT "THIS" IS "EXPANDED" OR THAT THE FOLLOWING LINE IS "COLLAPSED" 
    } 
    else { 
     $(this).removeClass('active'); 
     $(this).attr("id" ,"collapse"); 
    } 

    // toggle the display 
    $(this).parent().next('.toggle').toggle(); 
    return false; 
}); 

只需添加到這個... 我確實有這也在我們的測試網站其他地方使用的cookies的基本用法的理解。問題是,我知道如何使用它們的唯一方法是針對他們就像他們都低於...

// cookies 
// sidebar state 
var sideBar = $.cookie('sideBar'); 

// Set the user's selection for the left column 
if (sideBar == 'collapsed') { 
    $('#btnCollapseSidebar').css("visibility" ,"hidden"); 
    $('#btnExpandSidebar').css("visibility" ,"visible"); 
    $('#leftCol').css("visibility" ,"hidden");  
    $('#sidebar').css("visibility" ,"hidden"); 
    $('#rightCol').css("margin" ,"42px 0 0 45px"); 
}; 

的方式,我需要把它們作爲上面列出不能指定一個類,但實際項目(「這個」)。當我嘗試通過調整上述代碼來應用它們時,它會影響我的「.toggle」類的每個實例。 「.toggle」類將在頁面上多次使用,需要無限次地使用。

回答

1

使用jQuery Cookie插件實現起來非常簡單。 http://www.electrictoolbox.com/jquery-cookies/

var CookieOptions = { expires: 7, path: '/' } 
$.cookie("CookieName", "CookieValue", CookieOptions); 

通過這樣獲取的cookie:

$.cookie("CookieName"); 
+0

感謝您的輸入,但我認爲這是我們在別處使用Cookie的方式,我不知道如何應用於「這個「而不是」.aClass「。那有意義嗎?我的代碼將在頁面上使用「.toggle」無限次數。我不能瞄準「.toggle」,因爲它會針對每個實例。我需要能夠針對聲明的「這一部分」。 – bWhitham

+0

我不認爲這是一個答案排名爲「1」。雖然有很好的輸入,但是上面列出的答案對於我已經解決的一個簡單問題是一個非常簡單的解決方案。我遇到的問題是得到一個cookie來處理我在問題中代碼中列出的使用的切換。 – bWhitham