事件处理程序中的javascript全局变量
我正在尝试请求一个在 touchmove 函数内全局声明的变量,但出现引用错误。有人知道怎么回事吗?
function drawer(pulltab,drawer){
$('#pulltab').on('touchstart',function(e){
notworking=e.originalEvent.touches[0].pageX;
})
$(drawer).on('touchmove',function(loc){
var fingerloc=loc.originalEvent.touches[0].pageX;
var dist=fingerloc-notworking;
console.log(dist);
if (dist<0){
$(this).css('margin-left',dist);
}
})
$(drawer).on('touchend',function(){
$(this).css('transition','margin-left .1s');
$(this).css('margin-left',0);
})
}
drawer('#pulltab','#navigation-drawer');
请您参考如下方法:
I'm trying to request a variable declared globally inside of the touchmove function
您引用的代码中没有全局变量声明。
假设您还没有声明它,那么您正在 #pulltab
上的 touchstart
处理程序中创建(但不是声明)一个全局变量>:
notworking=e.originalEvent.touches[0].pageX;
使用The Horror of Implicit Globals * 创建一个全局的。但在该代码运行之前,全局不会存在。
显然,drawer
上的 touchmove
处理程序在 #pulltab 上的
。由于不存在名为 touchstart
处理程序之前触发notworking
的现有全局变量,因此您无法读取其值,并且会得到一个 ReferenceError
。如果 #pulltab
上的 touchstart
先执行,您就不会。
不要依赖隐式全局变量的恐怖。声明你的变量。如果你希望它是全局性的,把
var notworking;
...在所有功能之外。 (尽管全局变量是 Bad Thing™,但最好避免;如果您仅在 drawer
函数中使用 notworking
,并且不需要在对 drawer 的调用之间共享它
,只需在 drawer
中声明即可。)您可能还想在使用时检查它是否具有有用的值(value)。
* (这是我贫血的小博客上的帖子)
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。