我正在开发一个项目,我将函数设置为基于表单值创建cookie。然后该cookie填充另一个表单的输入值。起初,我只需要设置三个cookie,所以这不是太大(调用函数)......需求已经改变,我需要三个cookie到现在需要八个,所以我的函数调用得到了一点点失控。有更有效的方法吗?
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie(c, el) {
var user = getCookie(c);
if (user != "") {
document.getElementById(el).value = user;
document.getElementById(el).setAttribute("value", user);
document.getElementById(el).setAttribute("readonly", "readonly");
}
}
function setEmployee(e, field) {
var emp = getCookie(e);
if (emp != "") {
document.getElementsByClassName(field).value = emp;
var perm = document.getElementsByClassName(field);
perm[0].setAttribute("value", emp);
}
}
$(document).ready(function(){
var firstName = "firstName";
var lastName = "lastName";
var phoneCookie = "phone";
var emailCookie = "email";
var companyCookie = "company";
var addressCookie = "address";
var stateCookie = "state";
var zipCookie = "zip";
$('#form').submit(function(){
var first = $('#FirstName').val();
var last = $('#LastName').val();
var phone = $('#Phone').val();
var email = $('#Email').val();
var company = $('#Company').val();
var address = $('#Address').val();
var state = $('#State').val();
var zip = $('#PostalCode').val();
setCookie(firstName, first, 10);
setCookie(lastName, last, 10);
setCookie(phoneCookie, phone, 10);
setCookie(emailCookie, email, 10);
setCookie(companyCookie, company, 10);
setCookie(addressCookie, address, 10);
setCookie(stateCookie, state, 10);
setCookie(zipCookie, zip, 10);
});
if($('#census').is(':visible')){
checkCookie(firstName, "contactName");
checkCookie(lastName, "contactLast");
checkCookie(phoneCookie, "contactPhone");
checkCookie(emailCookie, "contactEmail");
checkCookie(companyCookie, "contactCompany");
checkCookie(addressCookie, "contactAddress");
checkCookie(stateCookie, "contactState");
checkCookie(zipCookie, "contactZip");
}
});