1

所以我正在尝试使用此方法在 PhoneGap 应用程序中对此进行测试:http: //inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/

当代码到达以下位置时,我不断收到参考错误: window.localStorage.setItemwindow.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'/>
4

1 回答 1

1

经过一番研究,在 PhoneGap 中默认启用了 localStorage。

我假设你得到的参考错误是由于这一行:

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

在调用它之前尝试检查数组是否存在:

if(window.localStorage.getArray('mysettings') !== undefined){
    var storedSettings = window.localStorage.getArray('mysettings');
else{
    var storedSettings = [] /*default settings and/or empty*/
}
于 2013-09-17T15:34:39.107 回答