0
function getFormState() {
    var fields = document.getElementsByTagName('form')[0].elements;
    if (fields.length === 0) {
        return;
    };
    for (var i = 0; i <= fields.length - 1; i++) {
        var name = fields[i].getAttribute('name');
        if (document.getElementByTagName('name').checked === true) {
            localStorage.setItem('name', "true");
        } else {
            localStorage.setItem('name', "false");
        }
    }
}

function fillFormState() {
    var fields = document.getElementsByTagName('form')[0].elements;
    if (fields.length === 0) {
        return;
    };
    for (var i = 0; i <= fields.length - 1; i++) {
        var name = fields[i].getAttribute('name');
        getStatus = localStorage.getItem('name'); {
            if (getStatus === "true") {
                console.log("its checked");
                document.getElementByTagName("name").setAttribute('checked', 'checked');
            } else {
                console.log("its not checked");
            }
        }
    }
} // run the below functions when the web page is loadedwindow.onload = function () {
// check if HTML5 localStorage is supported by the browser
if ('localStorage' in window && window['localStorage'] !== null) {
    // get the form state
    getFormState();
    // save the state of the form each X seconds (customizable)
    setInterval('fillFormState()', 1 * 1000);

}
};

但这似乎不起作用。我试图找出原因。我对javascript不是很有经验,所以它可能很明显。对此感到抱歉。我正在努力。

4

1 回答 1

0

我猜你localStorage永远不会因为这个循环而被设置:

for (var i = 0; i <= fields.length - 1; i++) {
    var name = fields[i].getAttribute('name');
    if (document.getElementByTagName('name').checked === true) {
        localStorage.setItem('name', "true");
    } else {
        localStorage.setItem('name', "false");
    }
}

没有document.getElementByTagName,你也在搜索"name"而不是你的变量name

for (var i = 0; i <= fields.length - 1; i++) {
    var name = fields[i].getAttribute('name');
    if (fields[i].checked === true) { //Check the current field
        localStorage.setItem(name, "true"); //Set the actual name, not "name"
    } else {
        localStorage.setItem(name, "false");
    }
}
于 2013-09-23T15:13:36.040 回答