我正在尝试将运动分配给事件侦听器外部的3个变量,但是事件侦听器内部的函数甚至似乎都没有运行。我也尝试过这样检查它:
if (window.DeviceMotionEvent) {
console.log("devicemotion was defined");
};
控制台记录了文本,但没有记录此文本:
var x, y, z;
var interval;
var arr = {'data':[]};
var ON = false;
window.addEventListener("devicemotion", function(event){
x = event.accelerationIncludingGravity.x;
y = event.accelerationIncludingGravity.y;
z = event.accelerationIncludingGravity.z;
console.log(x,y,z)
}
,true);
编辑: 此脚本代码位于模板目录中的html文件的底部。 html在Django上运行。
整个脚本(由于事件侦听器无法正常工作,部分脚本被注释掉了
<!--Clientside script-->
<script>
var x, y, z, alpha, gamma, beta;
var interval;
var arr = {'data':[]};
var ON = false;
window.addEventListener("devicemotion", function(event){
//x = event.accelerationIncludingGravity.x;
//y = event.accelerationIncludingGravity.y;
//z = event.accelerationIncludingGravity.z;
console.log(event)
}
,true);
window.addEventListener('deviceorientation', function(event){
alpha = event.alpha;
gamma = event.gamma;
beta = event.beta;
}
,true);
//Events that are running always
if (window.DeviceMotionEvent) {
console.log("devicemotion was defined");
};
if (window.DeviceOrientationEvent) {
console.log("GyroScope was defined");
};
$('input').on('click', function(){
if(ON==true){
ON=false;
} else {
ON=true;
}
});
//Main function,
//Creates list of sensor data.
function mainFunc(){ /*
if(ON=true){
interval = setInterval(() => {
arr['data'] = arr['data'].concat([x,y,z,alpha,gamma,beta]);
if(arr['data'].length >=30){
send();
console.log(arr);
}
console.log([x,y,z,alpha,gamma,beta]);
}, 200);
} else {
clearInterval(interval);
}
*/
}
//Ajax get request
//Checks for a response and animates the indicator accordingly.
function send(){
pack = arr['data'];
arr['data'].length = 0;
$.ajax({
url: "{% url 'detect' %}",
data: arr,
async: false,
success: function(data){
if (data==true){
$('#indicator').fadeIn('slow');
$('#indicator').fadeOut('slow');
}
}
})
};
</script>