Javascript 如何在新函数中再次使用变量
我使用这个函数在元素(.catch)中插入html,并且我只需要在一个新元素上捕获touch事件时执行这个函数,这与前一个不同 首先,我要捕捉触摸位置,接下来我要检查新id是否与前一个id的Javascript 如何在新函数中再次使用变量,javascript,jquery,variables,Javascript,Jquery,Variables,我使用这个函数在元素(.catch)中插入html,并且我只需要在一个新元素上捕获touch事件时执行这个函数,这与前一个不同 首先,我要捕捉触摸位置,接下来我要检查新id是否与前一个id的id!=lastid。但这不起作用,lastid未定义。在新元素上捕获触摸事件时,如何重新使用var lastid的值 var lastid ; $('.catch').bind('touchmove', function (evt) { var touch = evt.originalEvent.
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
隐藏起来,并在函数内部使其不可访问(您无法访问这两个值)
Javascript变量具有函数作用域
if ( element.hasClass('catch') && id != lastid)
{
//Changing the value
var lastid = id ;
// execute the rest of the function here
// ....
// ....
return lastid;
}
这将创建一个新的局部变量lastid,所需的变量将不会更新。删除“var”以将值赋给在函数的局部作用域之外声明的变量“lastid”
if ( element.hasClass('catch') && id != lastid)
{
//Changing the value
lastid = id ;
// execute the rest of the function here
// ....
// ....
return lastid;
}
要处理lastid的未定义状态,请使用一些合法值对其进行初始化。这里有一篇关于JavaScript中作用域的文章:那么,如果lastid是本地的,我如何检查这是否是一个新id?有没有办法使其全局化,以便在函数外部重用?还是应该以其他方式完成?好的,其他注释和链接帮助我找到了不同的问题。谢谢,但即使您进行了修改,在下次调用函数时它仍然未定义。您确定其他变量具有有效值,如
元素
和id
?你确定代码会进入你的if
语句,在那里lastid
被赋值吗?是的,是在代码的其余部分,在if
I有else
条件之后,再次改变变量lastid的范围。谢谢大家指出这个错误。
if ( element.hasClass('catch') && id != lastid)
{
//Changing the value
lastid = id ;
// execute the rest of the function here
// ....
// ....
return lastid;
}