0

I'm using this piece of code for my image slider...

$(document).ready(function() {

  $("#owl-demo").owlCarousel({
    jsonPath : 'json/customData.json',
    jsonSuccess : customDataSuccess,
    lazyLoad : true
  });

  function customDataSuccess(data){
    var content = "";
    for(var i in data["items"]){

       var img = data["items"][i].img;
       var alt = data["items"][i].alt;
       var myclass = data["items"][i].class;
       var link = data["items"][i].link;
     localStorage.setItem("imga", img);
     localStorage.setItem("alta", alt);
     localStorage.setItem("linka", link);
       content += "<a href=\""+link+"\"><img data-src=\"" +img+ "\" alt=\"" +alt+ "\" class=\"" +myclass+ "\"></a>"
    }
    $("#owl-demo").html(content);
  }


});

as soon I insert the localStorage element the script doesnt work anymore (the slider doesnt appear)... what I'm doing wrong ?

4

1 回答 1

0

Local Storage is supported in modern browsers.

If you are testing in Internet Explorer 7 or below it will not work.

Check HTML5 Web Storage for supported browsers.

I suggest looking at Modernizr to detect what features the browser supports and act accordingly. What I've done in the past is use localstorage if it's supported and fall back to using a cookie if it's not. Modernizr

UPDATE

$(document).ready(function () {

$("#owl-demo").owlCarousel({
    jsonPath: 'json/customData.json',
    jsonSuccess: customDataSuccess,
    lazyLoad: true
});

function customDataSuccess(data) {
    var content = "";
    for (var i in data["items"]) {

        var img = data["items"][i].img;
        var alt = data["items"][i].alt;
        var myclass = data["items"][i].class;
        var link = data["items"][i].link;
        localStorage.setItem("imga" + i, img);
        localStorage.setItem("alta" + i, alt);
        localStorage.setItem("linka" + i, link);
        content += "<a href=\"" + link + "?id=" + i + "\"><img data-src=\"" + img + "\" alt=\"" + alt + "\" class=\"" + myclass + "\"></a>"
    }
    $("#owl-demo").html(content);
}

});

So now the localstorage items will be in there individually, then what you will need to do on the new page is look up the items from localstorage with the id that's been passed via the querystring in the url.

The function on the new page that gets the id from the querystring then looks up the values in the localstorage could be something like this:

function getLocalStorageItem(id) {

   var img = localStorage.getItem("imga" + id);
   var alt = localStorage.getItem("alta" + id);
   var link = localStorage.getItem("linka" + id);

}

You will need to write the code to get the querystring value for the id parameter then pass that into the getLocalStorageItem function.

Obviously, this is a quick way - you will need to optimise this.

于 2013-11-01T11:36:58.770 回答