這裏是如何使用做HTML5 LocalStorage
$("#tempID").autocomplete({
source: function(req, resp) {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
resp(data);
}
});
$('#tempID').on('blur', function() {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
if($.trim(this.value).length > 0)
data.push(this.value);
localStorage.setItem('custom_history', JSON.stringify(data));
});
我在做什麼是將值設置爲HTML5本地存儲當用戶離開輸入字段,點擊其他地方。
然後檢索並設置爲jQuery UI自動完成的源。
這裏是工作提琴http://jsfiddle.net/joycse06/EBduF/173/
輸入一些值。點擊其他地方。再次點擊並添加其他值。刷新小提琴,並開始輸入其中一個和自動完成將顯示出來。
UPDATE
根據他的意見,後來聊天的最終代碼,他需要的就是這個,我如果可能別人後面
// if we dont set this line then ff will return null, and null.length will throw an error
if(!localStorage.getItem('custom_history'))
localStorage.setItem('custom_history','');
$("#test").autocomplete({
source: function(req, resp) {
var term = req.term;
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var intRegex = /^\d+$/;
data = $.map(data,function(val){
if(intRegex.test(val)){
if(val.indexOf(term) != -1)
return val;
else
return null;
}
else
return null;
});
resp(data);
}
});
$('#save').on('click', function() {
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var value = $.trim($('#test').val());
if(value.length > 0){
if($.inArray(value,data) != -1){
//alert('Duplicate');
return;
}
}
data.push(value);
localStorage.setItem('custom_history', JSON.stringify(data)); // set item to localStorage
});
NOP粘貼在,沒有任何的爲元素的歷史記錄添加值。但是,每次用戶點擊時,您都可以維護一個特殊的「數組」和「推」值,並在需要時將其拉回。 –
@Joy但是當用戶刷新頁面時,數組中的值將會丟失。有沒有其他的.. ?? – shashwat
然後,如果您希望在請求之間持續存在,那麼您已將其添加到cookie中。你可以使用這個插件https://github.com/carhartl/jquery-cookie –