Mam stronę z kilkoma polami wyboru. Przynajmniej kilka z nich i przejść do następnej strony, kiedy wrócę na tej stronie, te pola wyboru muszą pozostać jak były sprawdzane przed przechodząc na inną stronę. Trzeba to zrobić z JavaScript. Wszelkie trop ??
Utrzymywanie wartości checkbox
Musisz utrzymywać je między page-żądań. Można użyć sesji lub cookies, aby to zrobić. Jaki typ serwera pracujesz, i jaki rodzaj języka po stronie serwera?
Wcześniejsze pytania dotyczące SO mają zapis adresu / odczytu plików cookie z JavaScript.
Jeśli jesteś ograniczony tylko do JavaScript i bez języka po stronie serwera myślę, że są pozostawione do odczytu / zapisu plików cookie, aby utrzymać stan. Jak inni odwoływać, technologie po stronie serwera są znacznie lepsze w tym, ale jeśli musisz:
Przykładowy kod JavaScript cookies (referencyjna: 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);
}
Nie sądzę, że istnieje jakikolwiek rozsądnie skomplikowany sposób to zrobić bez żadnego dostępu do kodu po stronie serwera, ponieważ przy minimum Ci potrzebne do zainstalowania kodu, a także zidentyfikować formantów HTML, np w celu ich sprawdzenia. Jestem dając wystarczającą kod, który robi to, co chcesz poniżej.
Ważne notatki:
- Kod wymaga , aby każdy pole otrzymuje wyraźną cechę id.
- Stan wyboru jest przechowywany w pliku cookie o nazwie „JS_PERSISTENCE_COOKIE”. Byłoby lepiej, aby zapisać nazwę tego pliku cookie w zmiennej zamiast hardcoding go w kilku oddzielnych miejscach, jak Ja wam uczyniłem. Jaki rodzaj zmiennej należy zapisać nazwę zależy od aplikacji i wymagań.
- Byłoby lepiej, aby pakować kod wewnątrz obiektu, a nie jako grono wolnych funkcji jak Ja wam uczyniłem. Jednak to nie ma znaczenia do początkowego pytania.
- Po kliknięciu niektórych pól wyboru, można symulować „przechodząc z powrotem do tej strony” przez naciśnięcie klawiszy CTRL + F5. F5 nie wystarcza.
Oto kod HTML i niektóre próbki do badań:
<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>













