我正在尝试请求一个变量,这个变量是在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');发布于 2017-02-19 09:58:04
我正在尝试请求一个变量,该变量在touchmove函数中全局声明
在引用的代码中没有全局变量声明。
假设您没有声明它,那么您将在touchstart处理程序中在#pulltab上创建(但不是声明)一个全局变量
notworking=e.originalEvent.touches[0].pageX;它使用http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html*创建全局。但是在代码运行之前,全局是不存在的。
显然,touchmove在drawer上的处理程序在touchstart处理程序之前在#pulltab上触发。由于没有现有的全局名为notworking,所以无法读取其值,因此您将得到一个ReferenceError。如果touchstart on #pulltab先执行了,您就不会执行了。
不要依赖于隐含的全球化的恐怖。声明你的变量。如果您希望它是全球性的,请将
var notworking;...outside所有函数。(尽管全局变量是一件坏事,但最好避免;如果您只在notworking函数中使用drawer函数,并且不需要在对drawer的调用之间共享它,那么只需在drawer中声明它。)您也可能希望在使用它时检查它是否具有有用的价值。
*(这是我贫血的小博客上的一篇文章)
https://stackoverflow.com/questions/42325779
复制相似问题