javascript - 如何在新函数中再次使用变量

标签 javascript jquery variables

我正在使用此函数在元素 (.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/

相关文章:

javascript - 如何将变量从列表传递到 Sencha Touch 2 中的新 View

javascript - localForage 在 Chrome 中找到数据,在 Firefox 中找不到

javascript - 如何通过 react-arcgis npm 将图层添加到 arcgis map ?

javascript - 如何更改 SVG 图标的颜色?

jquery - 将自动完成列表中的国家/地区 Google map 限制为 "INDIA, USA and UK"

php - 在多个 css 文件中使用 php 变量

javascript - 从外部 div 单击时的 Jquery 和 Javascript 滚动图像

javascript - 如何改变 jQuery 中 .show() 方法的方向?

jquery - 在悬停时取消 substr

javascript - 存储/导入变量和函数处理(JS)