I have an event listener added in onDeviceReady to listen for back button event, and respond with stopWatch when it is pressed. However it responds when the app is started.
<!DOCTYPE html>
<html>
<head>
<title>UNH BSApp</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchAcceleration`
var watchID = null;
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
document.addEventListener("backbutton", stopWatch(), false);
startWatch();
}
// Start watching the acceleration
//
function startWatch() {
document.addEventListener("menubutton", stopWatch(), false);
// Update acceleration every 0.1 seconds
var options = { frequency: 10 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopWatch() {
alert("Hello!");
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
<style>
#start {
display:block;
border:solid;
}
</style>
</head>
<body>
<div id="accelerometer">Waiting for accelerometer...</div>
<div id="start">Start</div>
</body>
</html>
document.addEventListener("menubutton", stopWatch(), false);
This calls the stopWatch
function immediately. You want something like:
document.addEventListener("menubutton", stopWatch, false);
^^ no parens!
从侦听器的设置中删除()
-这是在调用函数而不将其作为参数传递:
document.addEventListener("menubutton", stopWatch, false);
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.