[英]can't access to a global variable in event handler method (javascript)
[英]javascript global variable in event handler
我正在尝试请求在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');
我正在尝试请求在touchmove函数内部全局声明的变量
您引用的代码中没有全局变量声明。
假设你没有申报,那么你正在创建 (但不声明)在一个全局变量touchstart
on处理#pulltab
:
notworking=e.originalEvent.touches[0].pageX;
它使用隐式全球性恐怖 *创建一个全局性。 但是,直到该代码运行,全局才会存在。
显然,在touchmove
上的touchstart
处理程序之前 , drawer
上的touchstart
处理程序正在#pulltab
。 由于不存在称为不工作的全局notworking
,因此您无法读取其值,并且会收到ReferenceError
。 如果touchstart
上的#pulltab
首先执行,则不会。
不要依赖隐式全局变量的恐怖。 声明变量。 如果您希望它具有全球性,请放
var notworking;
...所有功能之外 (虽然全局变量是一件坏事™最好避免使用,如果你只使用notworking
的内drawer
的功能,你不需要它调用之间共享drawer
,只是内声明它drawer
。)您可能还需要使用时检查,它是否具有有用的价值。
* (这是我贫乏的小博客上的帖子)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.