使用本地存儲,以應對以後的使用
HTML
<textarea name="userText" id="description" cols="30" rows="10"></textarea>
<div class="character-count"></div>
jQuery的
$(function(){
var comment = $('#description');
var val = localStorage.getItem(comment.attr('id')),
max = 4000,
len = val.length,
left = (max - len) ;
// if the value exists, set it
if (val) {
comment.val(val);
$('.character-count').text(left + ' Character(s) left');
}
});
$('#description').on('keyup', function (e) {
var $this = $(this),
max = 4000,
val = $this.val(),
val_length = val.length,
remain = ((max - val_length)>=0)?(max - val_length):0;
$('.character-count').text(remain + ' Character(s) left');
if(val_length > max){
$this.val(val.slice(0,max));
}
// let's check if localStorage is supported
if (window.localStorage) {
localStorage.setItem($(this).attr('id'), $(this).val());
}
});
SEE DEMO
設置在'cookie' – coolguy