Javascript 를 사용하여 설정할 수 있으며, 쿠키 (cookie

39 m i& 하고, 내가 원하는 쿠키를 설정되었습니다 CSS 파일 따라 내 HTML. I have a 형 CSS 파일 목록이 있는 옵션 및 다른 값으로. 내가 원하는 파일을 저장할 때 쿠키 일주일 정도 한다. 이전 파일을 열면 HTML 파일을 저장할 수 있다는 것입니다 you& # 39, ve 선정됐다.

자바스크립트 코드:

function cssLayout() {
    document.getElementById("css").href = this.value;
}

function setCookie(){
    var date = new Date("Februari 10, 2013");
    var dateString = date.toGMTString();
    var cookieString = "Css=document.getElementById("css").href" + dateString;
    document.cookie = cookieString;
}

function getCookie(){
    alert(document.cookie);
}

HTML 코드:

<form>
    Select your css layout:<br>
    <select id="myList">
        <option value="style-1.css">CSS1</option>
        <option value="style-2.css">CSS2</option>  
        <option value="style-3.css">CSS3</option>
        <option value="style-4.css">CSS4</option>
    </select>
</form>
질문에 대한 의견 (5)

다음과 같은 코드를 다운로드합니까 것보다 훨씬 많을 것으로 간단해진다는 다른 사항은요:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(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) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

이제 함수 호출 ,

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

출처 - http://www.quirksmode.org/js/cookies.html

그래서 그들은 오늘날 모든 페이지에 업데이트된 페이지에 최신값 현재 합니다.

해설 (22)
    • 것보다 훨씬 더 많이 그것은꿈의 참조입니다 w3schools (가장 큰 지금까지 만들어진 웹 참조).

이러한 참조용이므로 파생됨 참조:

// sets the cookie cookie1
document.cookie =
 'cookie1=test; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie =
 'cookie2=test; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

아무리 좋은 쿠키 () 는 모질라 참조입니다 라이브러리를 사용할 수 있습니다.

해설 (14)

39 m 이 질문에 답을 해야 합니다, 좀 더 일반적인 i& 재사용 가능한 코드를 사용할 수 있는 일부 쿠키를 key-value 쌍.

1 에서 [매든] 는 트루스터블 아마 이 스니핏을 가져옵니다. 이것은 객체에 대한 utf 안전하다구요 작동합니까 쿠키:

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

모든 경우에 이 작동 테스트는 mizilla 증명할 수 있다.

There is an 교체품 스니핏 here:

해설 (6)

[JavaScript 쿠키를 확인란 W3Schools.com] [1] 값을 통해 점점 쿠키 설정을 위한 JS.

그냥 세스쿠키 사용 방법 및 제쿨키 언급되지 않았다.

따라서 코드를 모양은 다음과 같습니다.


<script>
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function cssSelected() {
    var cssSelected = $('#myList')[0].value;
    if (cssSelected !== "select") {
        setCookie("selectedCSS", cssSelected, 3);
    }
}

$(document).ready(function() {
    $('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
    --Select--
    CSS1
    CSS2
    CSS3
    CSS4
해설 (9)