简体   繁体   中英

PhoneGap javascript localStorage Android

So I'm trying to test this in a PhoneGap application using this method: http://inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/

I keep getting a reference error when the code gets to the: window.localStorage.setItem and window.localStorage.setArray

JS:

Storage.prototype.setArray = function (key,obj) {
    return this.setItem(key, JSON.stringify(obj));
}
Storage.prototype.getArray = function (key) {
    return JSON.parse(this.getItem(key));
}

var storedSettings = window.localStorage.getArray('mysettings');

alert('storedSettings = ' + storedSettings);
  if (storedSettings === null) {
      var settings = newArray();
  } else {
      var settings = storedSettings;
  }

$(document).ready(function() {



$('input[type=submit]').click(function() {
    alert('sup');
    var xsize = $('input[name=rads]:checked').attr('id');
    var xfirstname = $('#fname').val();
    var xsex = $('input[name=mf]:checked').attr('id');

    settings.push({'size':xsize, 'fname':xfirstname, 'sex':xsex});
    window.localStorage.setItem('mysettings', settings);
    window.localStorage.setArray('mysettings', settings);
    alert('settings:\n#1: ' + settings[0] + '\n#2: ' + settings[1] + '\n#3: ' + settings[2]); 
});



});

HTML:

<label for='small'>small</label>
<input type='radio' name='rads' id='small' checked='checked'/><br/>

<label for='medium'>medium</label>
<input type='radio' name='rads' id='medium'/><br/>

<label for='large'>large</label>
<input type='radio' name='rads' id='large'/>
<br/>
<br/>

<input type='text' id='fname' size='10'/>
<br/>

<label for='male'>M:</label>
<input type='checkbox' id='male' name='mf' checked='checked'/>
<br/>

<label for='female'>F:</label>
<input type='checkbox' id='female' name='mf'/>
<br/>
<br/>

<input type='submit' onclick='goset();' value='Save Settings'/>

After some research, localStorage is enabled by default in PhoneGap.

I assume the reference error you're getting is due to this line:

var storedSettings = window.localStorage.getArray('mysettings');

Try checking to see if the array exists before calling it:

if(window.localStorage.getArray('mysettings') !== undefined){
    var storedSettings = window.localStorage.getArray('mysettings');
else{
    var storedSettings = [] /*default settings and/or empty*/
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM