下面的代码成功地创建了字符串值为"XinputX"的cookie。但是,我希望它是用户输入的值。
我还需要通过相同的点击转到另一个页面,如果 onSubmit 已经用于设置 cookie,我将把该操作放在哪里?
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);
}
<div class="container-fluid">
<div class="row">
<div class="d-flex mx-auto mt-5 mb-5">
Hello and welcome to the quiz.
</div>
</div>
<div class="row">
<div class="d-flex mx-auto mb-5">
<form onsubmit="createCookie('first_cookie','XinputX',7)">
Enter name:
<input type="text">
<input type="submit">
</form>
</div>
</div>
<div class="row">
<div class="col-12 col-sm-6 mx-auto">
<button type="button" id="nextQuestion" class="btn btn-primary d-flex mx-auto mt-2">Lets go!</button>
</div>
</div>
</div>
- "去别的地方"可以通过添加操作或在脚本中完成。
- 如果您不想使用该操作,则需要取消提交
我已将 cookie 代码替换为控制台.log因为 SO 不允许设置 cookie。只需在上传时删除//
我还命名了该字段并给表单一个 ID
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=/";
console.log("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);
}
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission, remove this if you add an action to the form
createCookie('first_cookie', this.textField.value,7);
// if you do not want to use the action attribute of the form you can do this:
// window.location="somewhereelse.html";
});
});
<div class="container-fluid">
<div class="row">
<div class="d-flex mx-auto mt-5 mb-5">
Hello and welcome to the quiz.
</div>
</div>
<div class="row">
<div class="d-flex mx-auto mb-5">
<form id="myForm">
Enter name:
<input name="textField" type="text">
<input type="submit">
</form>
</div>
</div>
<div class="row">
<div class="col-12 col-sm-6 mx-auto">
<button type="button" id="nextQuestion" class="btn btn-primary d-flex mx-auto mt-2">Lets go!</button>
</div>
</div>
</div>