Made a http://jsfiddle.net/ddvQU/30/ jsfiddle that counts the clicks in a div area.

 <textarea id="ta" placeholder="Type your text here..."></textarea>
 <p id="ta-log"></p>

I am looking to store that number of clicks so when the user navigates away from the page (Closes it) I can recall the number from localstorage.

有帮助吗?

解决方案

I've updated your jsfiddle and it does what you want:

$( function() {
    var clickCount = localStorage.getItem('clickCount');
    clickCount = clickCount ? parseInt(clickCount) : 0;
    var $num = $('.num');
    $num.text(clickCount);
    $('.box').click( function() {
        $num.text(++clickCount);
        localStorage.setItem('clickCount', clickCount);
    });
});

I haven't used try ... catch blocks, but in real life you should, as you could get errors trying to access localStorage, because it can be disabled or you could have consumed your disk quota.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top