简体   繁体   中英

Storing previous event.target.id in a variable

I am in a situation where I need to keep track of the previously clicked event.target.id that is firing the click event.

A very simple example of my code is as follows (I am using dojo and jQuery):

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

This code keeps overwriting the lastActiveTool variable with the current event id. However, I need a way to keep track of the previous one.

Sorry if this is a silly question, I am still learning 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;
}

Firstly you shouldn't declare your variable inside the function as it'll only be accessible inside that function and since it's an anonymous function, it'll be destroyed each time the function is done running.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM