我网站展现的是缓存页面,之前有个问题就是不动态的话,wp无法动态定义cookie来记住用户表单信息。只有自己在js中加入相关的记住信息了:

cookie版:

/*
张戈博客:https://zhangge.net/4538.html
*/
function getCookie(c_info) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_info + "=");
        if (c_start != -1) {
            c_start = c_start + c_info.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 null;
}

function removeCookie(name) {
    var cval = getCookie(name);
    if (cval != null) {
        setCookie(name, cval, -1);
    }
}

function setCookie(c_info, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_info + "=" + escape(value) + ";path=/;domain=www.xinroom.cn" + (typeof expiredays == "undefined" ? "" : "; expires=" + exdate.toGMTString());
}

function checkCookie() {
    $("#comment-author-info input[type='text']").each(function() {
        var val = getCookie(this.name);
        this.value = val;
    });
}

function goSubmit() {
    $("#comment-author-info input[type='text']").each(function() {
        removeCookie(this.name);
        setCookie(this.name, this.value, 365);
    });
}

$(document).ready(function() {
    checkCookie();
    $("#respond #submit").click(function() {
        goSubmit();
    });
});

相应的注意事项,原博客有。

local storage版

因为我喜欢精简代码,我网址的html、js、css、php都被我精简了个遍^_<,同时localstorage还有个好处就是在http请求时部携带相应的值,而cookie就会增加http-header(虽然好像也不多),所以就自己用local storage代替了

$(document).ready(function() {
    $("#comment-author-info input[type='text']").each(function() {
        this.value = localStorage.getItem(this.name);
    }), $("#respond #submit").click(function() {
        $("#comment-author-info input[type='text']").each(function() {
            localStorage.setItem(this.name, this.value);
        });
    });
});

注意

#comment-author-info为包含name、Email、url输入框的大div层,如果主题没有,可自行加上。

更新于:2017-11-25