kutusunun değerlerinin kalıcılığı

oy
2

Birkaç onay kutularını içeren bir sayfa var. Ben bu onay kutuları onlar başka bir sayfaya gitmeden önce olduğu gibi kontrol edilmeleri gerekmektedir, birkaç tanesi kontrol ve ben bu sayfadaki döndüğümde, bir sonraki sayfaya gidin. JavaScript ile yapmak gerekiyor. Bir ipucu??

Oluştur 20/07/2009 saat 16:28
kaynak kullanıcı
Diğer dillerde...                            


3 cevaplar

oy
1

Sen sayfa istekleri arasında bunları kalıcı gerekir. Bunu yapmak için oturum veya tanımlama bilgilerini kullanabilir. ne tür sunucu üzerinde çalışmakta ve sunucu tarafı dili ne tür ile var?

JavaScript çerezleri okuma / adres yazma sahip SO üzerinde Önceki sorular.

Cevap 20/07/2009 saat 16:30
kaynak kullanıcı

oy
4

Yalnızca JavaScript ve hiçbir sunucu tarafı dili sınırlama varsa sana durumunu korumak için / yazma çerezleri okumak için bırakılır düşünüyorum. Diğerleri başvurulan gibi, sunucu tarafında teknolojileri Gerekirse çok bunda iyi ama şunlardır:

JavaScript çerez örnek kod (referans: http://www.quirksmode.org/js/cookies.html ):

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}
Cevap 20/07/2009 saat 16:37
kaynak kullanıcı

oy
0

Ben en azından nedeniyle sunucu tarafı kodunda herhangi erişimi olmadan bunu yapmak için herhangi bir makul karmaşık bir yolu vardır sanmıyorum gerek kodunuzu yükleyip bunları da kontrol etmek için örneğin HTML kontrolleri tanımlamak için. Ben aşağıda istediğini yapar makul kodu veriyorum.

Önemli notlar:

  1. Kod gerektiren her onay kutusu ayrı id özelliğini verildiği.
  2. çek devlet 'JS_PERSISTENCE_COOKIE' adlı bir çerez saklanır. Benim yaptığım gibi ayrı yerlerde birkaç içinde hardcoding yerine bir değişkene bu çerezin adını depolamak için daha iyi olurdu. adını depolamak gerekir değişkenin ne tür uygulamanıza ve gereksinimlerine bağlıdır.
  3. Benim yaptığım gibi bir nesnenin içine yerine serbest fonksiyonları bir demet olarak kod paketlemek daha iyi olurdu. Ancak, bu ilk soruya alakalı değildir.
  4. Bazı onay kutularını tıkladıktan sonra CTRL + F5 vurarak "Bu sayfaya geri dönme" benzetilebilir. yalnız F5 yeterli değildir.

İşte kod ve test için bazı örnek HTML var:

<body onload="restorePersistedCheckBoxes()">
    <input type="checkbox" id="check1" onclick="persistCheckBox(this)" />
    <input type="checkbox" id="check2" onclick="persistCheckBox(this)" />
    <input type="checkbox" id="check3" onclick="persistCheckBox(this)" />
    <input type="button" value="Check cookie" 
           onclick="alert(document.cookie)" />
    <input type="button" value="Clear cookie"
           onclick="clearPersistenceCookie()" />

    <script type="text/javascript">
        // This function reads the cookie and checks/unchecks all elements
        // that have been stored inside. It will NOT mess with checkboxes 
        // whose state has not yet been recorded at all.
        function restorePersistedCheckBoxes() {
            var aStatus = getPersistedCheckStatus();
            for(var i = 0; i < aStatus.length; i++) {
                var aPair = aStatus[i].split(':');
                var el = document.getElementById(aPair[0]);
                if(el) {
                    el.checked = aPair[1] == '1';
                }
            }
        }

        // This function takes as input an input type="checkbox" element and
        // stores its check state in the persistence cookie. It is smart
        // enough to add or replace the state as appropriate, and not affect
        // the stored state of other checkboxes.    
        function persistCheckBox(el) {
            var found = false;
            var currentStateFragment = el.id + ':' + (el.checked ? '1' : '0');
            var aStatus = getPersistedCheckStatus();
            for(var i = 0; i < aStatus.length; i++) {
                var aPair = aStatus[i].split(':');
                if(aPair[0] == el.id) {
                    // State for this checkbox was already present; replace it
                    aStatus[i] = currentStateFragment;
                    found = true;
                    break;
                }
            }
            if(!found) {
                // State for this checkbox wasn't present; add it
                aStatus.push(currentStateFragment);
            }
            // Now that the array has our info stored, persist it
            setPersistedCheckStatus(aStatus);
        }

        // This function simply returns the checkbox persistence status as
        // an array of strings. "Hides" the fact that the data is stored
        // in a cookie.
        function getPersistedCheckStatus() {
            var stored = getPersistenceCookie();
            return stored.split(',');
        }

        // This function stores an array of strings that represents the 
        // checkbox persistence status. "Hides" the fact that the data is stored
        // in a cookie.
        function setPersistedCheckStatus(aStatus) {
            setPersistenceCookie(aStatus.join(','));
        }

        // Retrieve the value of the persistence cookie.
        function getPersistenceCookie()
        {
          // cookies are separated by semicolons
          var aCookie = document.cookie.split('; ');
          for (var i=0; i < aCookie.length; i++)
          {
            // a name/value pair (a crumb) is separated by an equal sign
            var aCrumb = aCookie[i].split('=');
            if ('JS_PERSISTENCE_COOKIE' == aCrumb[0]) 
              return unescape(aCrumb[1]);
          }
          return ''; // cookie does not exist
        }

        // Sets the value of the persistence cookie.
        // Does not affect other cookies that may be present.
        function setPersistenceCookie(sValue) {
            document.cookie = 'JS_PERSISTENCE_COOKIE=' + escape(sValue);
        }

        // Removes the persistence cookie.
        function clearPersistenceCookie() {
            document.cookie = 'JS_PERSISTENCE_COOKIE=' +
                              ';expires=Fri, 31 Dec 1999 23:59:59 GMT;';
        }
    </script>

</body>
Cevap 20/07/2009 saat 17:26
kaynak kullanıcı

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more