我想将 HTML 输入标记中的用户输入存储为 cookie 以供稍后使用。当用户单击按钮时,我需要读取多个输入框并存储文本值。
我的问题是,从我使用alert(document.cookie)看到的情况来看,将信息保存到cookie似乎无法正常工作,而是没有保存任何信息
HTML 代码:
<form id="contact-form">
<label for="name">Log entry name:</label>
<input type="text" id = "eName" value="" placeholder="Run at the park"/>
<label for="email">Name of exercise:</label>
<input type="name" id = "exercise" value="" placeholder="Jogging" />
<label for="telephone">Date: </label>
<input type="number" id = "date" value="" />
</form>
<li><a href="#" onclick ="setCookie()"> Add New Log</a></li>
<li><a href="#" onclick ="getCookie()"> cookie</a></li>
JavaScript:
<script type = "text/JavaScript">
function setCookie(){
var cookieString = "entry=" + document.getElementById("eName").value +
";exercise=" + document.getElementById("exercise").value +
";date=" + document.getElementById("date").value ;
document.cookie = cookieString;
}
function getCookie(){
alert(document.cookie);
}
当我将 cookie 显示为警报时,这是响应:
最佳答案
您无法使用 document.cookie
读取 cookie。
要读取 cookie,请使用:
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
关于JavaScript:设置 cookie 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840311/