To retain certain preferences or user information across multiple sessions, you may want to utilize cookies. In JavaScript, setting and retrieving cookies is a straightforward task.
To set a cookie with a specific name, value, and expiration time:
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=/"; }
To retrieve a cookie by its name:
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; }
In your HTML file:
<select>
In your JavaScript file:
// Set the cookie when the user selects a CSS file function setCSSLayout() { var cssFile = document.getElementById("myList").value; setCookie("cssFile", cssFile, 7); } // Get the cookie and set the CSS file accordingly function getCSSLayout() { var cssFile = getCookie("cssFile"); if (cssFile) { document.getElementById("css").href = cssFile; } } // Load the previously selected CSS file window.onload = function () { getCSSLayout(); };
By utilizing these functions, you can easily set and retrieve cookies in JavaScript, allowing you to store user preferences and enhance your web applications.
The above is the detailed content of How Can I Set and Retrieve Cookies Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!