2

I am creating a crossword puzzle web app that pulls XML data from a server, parses the data with javascript and builds the puzzle on the page using the [canvas] tag. When a user selects a clue and types in a correct answer, letters are placed in the corresponding squares of the crossword puzzle.

Here's a snippet of the code that places the letters in the corresponding squares:

function answer() {
if (this.value != '') {
    var letters = this.value.split('');
    var correct = xmlhttp.responseXML.getElementsByTagName(node)[0].getAttribute('a').split('');
    var numCorrect = 0;
    for (var i = 0; i < selected.length; i++) {
        if (letters[i]) {
            if (letters[i].toUpperCase() == correct[i]) {
                eval('ctx.drawImage(i'+letters[i].toLowerCase()+'b, '+((selected[i].id%15)*26)+', '+(Math.floor(selected[i].id/15)*26)+')');
                matrix[selected[i].id] = 1;
                numCorrect++;
            } else {
                matrix[selected[i].id] = 0;
            }
        }
    }       
    if (numCorrect == correct.length) {
        alert('Correct!');
        clearSelection();

    } else if (numCorrect == 0) {
        alert('Incorrect, try again.');
        document.getElementById('answer').value = '';
        document.getElementById('answer').focus();
    } else if (numCorrect != correct.length) {
        alert('Only some letters are correct.');
        clearSelection();
    }
    checkForWin();      
}
}

My question is, how do I save the state of the puzzle and the XML (using HTML5 web storage) so that the user can play offline and to prevent them from losing their progress in the event of a browser refresh?

Can anyone help me with this one, I am not very familiar with the HTML Web Storage API...but I hear that it is a valuable tool for web apps. Your advice will be much appreciated.

Thanks, Carlos

4

2 回答 2

1

您可以使用以下 javascript 将 JSON 对象或程序状态保存在 html5 本地存储中:

if(localStorage)
 localStorage.setItem("NAME", JSON/XML Object);

然后您可以稍后使用

var savedGame = localStorage["NAME"];

不过有一个警告,它适用于除 IE 之外的所有浏览器,因为它们使用其他东西作为本地存储。

于 2011-08-29T03:19:17.430 回答
0

除非您的应用程序的其余部分依赖于 HTML5,否则您可能会考虑使用像Lawnchair这样的库来包装 localStorage,但也可以为其他具有存储机制但没有 localStorage 的浏览器提供替代实现。如果您确实使用 Lawnchair,那么我建议您将其与lccache配对。

如果您决定跳过 Lawnchair 并仅使用 localStorage,那么我建议您将其与lscache 配对。lscache 和 lccache 都是将 API 简化为简单的包装器:

value = l(c/s)cache.get("key");

l(c/s)cache.set("key", value);

l(c/s)cache.remove("key");

这就像保存东西、把它拿出来等一样简单。另外,对于你只想存储一段时间的东西。当您将它与一组一起放入缓存时,您可以指定它过期的时间。

于 2011-08-29T04:11:41.590 回答