如何使用HTML5'使用Jquery的本地存储's select2插件

How to use HTML5's localstorage with Jquery's select2 plugin

本文关键字:存储 插件 select2 Jquery 何使用 HTML5 使用      更新时间:2023-09-26

有没有办法将HTML5的本地存储方法与Jquery的select2插件一起使用?现在,当我输入数据并关闭浏览器/选项卡时,所有输入的数据都不见了,这不是最理想的,因为如果你不记得你输入了什么,它会让人困惑

我的select2代码如下:

$(".select").select2({
minimumInputLength: 1,
multiple: true,
query: function(query){
    $.getJSON( 'url path to remote API', {
      name:query.term, 
      featured:true
     }, function(results){
        var data = {results: []};
        $.each(results.data, function(index, item){
            data.results.push({id: item.artist_id, text: item.name});
        });
        query.callback(data);   
     } );
}
}); 

任何帮助都非常感谢

尝试一下:http://jsfiddle.net/7267rkxy/12/

我为你评论了代码,以解释正在发生的事情,你应该可以用query选项替换data选项,它应该仍然可以工作

附言:我注意到你回答的问题都没有被标记为"已接受",如果有人给了你一个你喜欢的或对你有用的答案,你应该点击答案旁边的复选框,将他们的答案标记为"接受"


HTML

<!-- setting a hard width for example -->
<input type="text" class="select" style="width:200px;" value="" />

JS-

// set value property to local storage value
$(".select").val(localStorage.s2options);
$(".select").select2({
minimumInputLength: 1,
multiple: true,
data: [{id: 1, text: 'option1'},{id: 2, text: 'option2'},{id: 3, text: 'option3'}], //sample data
initSelection: function (element, callback) {
    // initSelection only fires when there is something in the value property
    callback($.parseJSON(element.val()));
}
}).on('change', function(info){
   // checking if we have anything stored in local storage
   var s2options = localStorage.s2options ? JSON.parse(localStorage.s2options) : [];
   // add / remove options
   if (info.added) {
       s2options.push(info.added);
   } else if (info.removed) {
       s2options = s2options.filter(function(opt) {
           return opt.id != info.removed.id;
       });
   }
    // save selections to local storage
    localStorage.s2options = JSON.stringify(s2options);
});

除了@bruchowski的答案外,Select2的新版本还有不同的方法(尽管initSelectionquery仍然支持向后兼容性):

您必须创建一个自定义DataAdapter并实现current()query()