我們正在使用PhoneGap開發使用iPhone加速度計的計步器應用程序。爲什麼獲取LocalStorage項目產量「未定義」?
下面是我們當前正在運行的代碼的副本:
<!DOCTYPE html>
<html>
<head>
<title>Accelerometer</title>
<script type="text/javascript" charset="utf-8" src="js/cordova-1.7.0rc1.js"></script>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchAcceleration`
var watchID = null;
var stepCount = 0;
window.localStorage.setItem('exp');
var expGain = 0;
var totalExp = window.localStorage.getItem('exp');
var userAge = window.localStorage.getItem('age');
var handicap = 0;
if (userAge <= 10) {
handicap = 10;
} else if (userAge > 10) {
handicap = 5;
}
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//e7
function onDeviceReady() {
startWatch();
}
// Start watching the acceleration
//
function startWatch() {
// Update acceleration every 5 seconds
var options = {
frequency: 1000
};
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
//count steps and calculate experience gained
function countSteps(accelx, timestamp, expGain, totalExp) {
var element = document.getElementById('accelerometer');
//var accCount = Math.round(acceleration.x);
//stepCount = stepCount + Math.abs(accCount);
stepCount = stepCount + 1;
expGain = stepCount * handicap;
totalExp = totalExp + expGain;
//window.localStorage.setItem('exp', totalExp);
element.innerHTML = '<br>Step Count: ' + stepCount + '<br/>' +
'Acceleration X: ' + Math.abs(accelx) + '<br />' +
'Timestamp: ' + timestamp + '<br />' +
'Experience: ' + totalExp + '<br />';
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
var accelx = Math.round(acceleration.x)
var timestamp = acceleration.timestamp
//element.innerHTML = 'Acceleration X: ' + Math.abs(accelx) + '<br />' +
//'Acceleration Y: ' + acceleration.y + '<br />' +
//'Acceleration Z: ' + acceleration.z + '<br />' +
//'Timestamp: ' + acceleration.timestamp + '<br />';
if (Math.abs(accelx) > 1) {
countSteps(accelx, timestamp, expGain, totalExp);
}
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
<link media="only screen and (max-device-width: 480px)" href="css/iPhone.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="accelerometer">Waiting for accelerometer...</div>
<button onclick="startWatch();">Start Watching</button>
<button onclick="stopWatch();">Stop Watching</button>
<br />
<p><a href="index.html">back</a>
</p>
</body>
</html>
的問題是:我們不斷收到"undefined"
旁邊,我們對結果window.localStorage.setItem('exp');
。我們一整天都在努力嘗試和解決這個問題。
爲什麼在發現第3行錯誤之前編寫了所有代碼? – RobG
,因爲我們每週只能訪問一次uni –
Geeze,我記得那些日子...... 100行Fortran花了一個小時編譯,結果在打印機上出來...... CS學生的資源不是優先權。 – RobG