Jquery localstorage checkbox



我是jquery的新手,我想知道你是否可以帮助我。我正在设置一个网页,该网页从 .json 文件中导入前 100 个 imdb 列表,并从另一个 .json 文件中导入详细信息。我已经设法做到了这一点,但我很难将本地存储与我的所有复选框一起使用。我希望能够通过单击复选框来存储我看过的电影,并且我希望页面在我再次使用它时记住。我也是堆栈溢出的新手,所以我希望我做得对。

这是我到目前为止的jquery代码!

$(document).ready(function() {
    $.getJSON('movies.json', function(result) {
        $.each(result, function(index, movie){
            $.getJSON('details/' + movie.id + '.json', function(details) {
                $('#movies').append("<div class='movie' id='" + movie.id +"'>" +
                '<p><input type="checkbox" class="checkbox" id='+ movie.id + ' name="myCheckbox"/> <p id=' 
                + movie.id + '><p class="movietitle" id ='+ movie.id +'>'+ movie.title +'</p></p></p>' +
                        "<div class='info' id='" + movie.id +"'>" +
                            '<p> Country:' + details.country + '</p>' +     
                            '<p> Year:' + details.year + '</p>' + 
                            '<p> Rating:' + details.rating + '</p>' +
                            '<p> Languages:' + details.languages + '</p>' +
                            '<p> Rating:' + details.rating + '</p>' +
                            '<a class="imdb" href =" '+ details.imdburl + ' ">Skoðaðu myndina á imdb</a>' + 
                        "</div>" +  
                    "</div>"
                    );
            });
        });
    });
});

抱歉,阅读后不得不重写,并意识到我在某一点上错了,可以简化这一点。你快到了,但不是id='movie.id'(或补充(来简化它,它应该是value='movie.id'。

所以:

<input type="checkbox" class="checkbox" value='+ movie.id + ' name="myCheckbox"/> 
如果要在选中

/取消选中某些内容时获取值数组,然后存储它:

$("input[type='checkbox']").change(function(){
 var movieIDs = $("input:checkbox:checked").map(function(){
   return $(this).val();
}).get();
 localStorage['movieList'] = JSON.stringify(movieIDs);
});

然后当您要检索时:

var movieList = JSON.parse(localStorage["movieList"]);

例如,要在加载时显示已检查/查看的电影:

var movieList = (localStorage["movieList"]) ? JSON.parse(localStorage["movieList"]) : [];
$("input[type='checkbox']").each(function(){
    if($.inArray($(this).attr('id'), movieList) >= 0)
    {
        $(this).attr('checked', true);
    }           
});

请参阅此处的 JSFiddle(已更新(: http://jsfiddle.net/thespacebean/SdcLr/5/

现在,如果您重新加载页面,您以前的选择仍将显示。

最新更新