将以前的事件.target.id存储在变量中

Storing previous event.target.id in a variable

本文关键字:存储 变量 id target 事件      更新时间:2023-09-26

我需要跟踪上次单击的事件.target.id,该事件正在触发单击事件。

我的代码的一个非常简单的例子如下(我使用的是dojo和jQuery):

on(dom.byId("div-tools-draw"), "click", function (evt) {
    var lastActiveTool = evt.target.id;
}

这段代码不断用当前事件id覆盖lastActiveTool变量。但是,我需要一种方法来跟踪上一个。

很抱歉,如果这是一个愚蠢的问题,我还在学习JS。

var lastActiveTool;
on(dom.byId("div-tools-draw"), "click", function (evt) {
   //do whatever you want with previous value if there is one
   lastActiveTool = evt.target.id;
}

首先,您不应该在函数中声明您的变量,因为它只能在该函数中访问,而且由于它是一个匿名函数,每次函数运行完毕时,它都会被销毁。

var lastActiveTool;
on(dom.byId("div-tools-draw"), "click", function (evt) {
    if(typeof lastActiveTool !== 'undefined'){
        //Do what you need to do with the last id. Add an else if you want something special to happen when the first element is clicked and there is no previous id.
    }
    lastActiveTool = evt.target.id;
}