我正在使用此函数在元素 (.catch) 中插入 html,并且我需要仅在新元素上捕捉到触摸事件时才执行此函数,不同于之前的元素。
首先我要捕捉触摸位置,接下来我要检查新 ID 是否不同于以前的 ID id != lastid
。但这不起作用,lastid 是未定义。当在新元素上捕获触摸事件时,如何重新使用 var lastid
的值?
var lastid ;
$('.catch').bind('touchmove', function (evt) {
var touch = evt.originalEvent.touches[0];
var element = $(document.elementFromPoint(touch.clientX, touch.clientY));
var id = document.elementFromPoint(touch.clientX, touch.clientY).id;
if ( element.hasClass('catch') && id != lastid){
//Changing the value
lastid = id ;
// execute the rest of the function here
// ....
// ....
return lastid;
}
});
谢谢!
编辑:var lastid = id ;
最佳答案
不要在函数内部使用 var
。只需使用 lastid = id
,指定 var
在闭包内再次声明它 另一个同名变量(即函数)隐藏在函数外部声明的 lastid
并使其在函数内部不可访问(您无法访问这两个值)
//Changing the value
lastid = id ;
关于javascript - 如何在新函数中再次使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52649745/