I can't understand why one solution works and the other doesn't. The list is a Map with three different values. From it, I build a structure with 3 div blocks and add an event on click. This one example doesn't work; it adds an event listener only to the last block from the list:
function create_struct(list, parent){
let _struct = new Map();
let el;
list.forEach((value, key, list)=>{
el = $( "<div/>", {id: key, class: "TAB_CAPTION"}).appendTo(parent);
el.on({
"click": function(){
el.removeClass("active");
el.addClass("active");
}
});
_struct.set(key, el);
});
return _struct;
};
However, this one using Map without variables works fine, and I don't understand why!
function create_struct(list, parent){
let _struct = new Map();
let el;
list.forEach((value, key, list)=>{
el = $( "<div/>", {id: key, class: "TAB_CAPTION"}).appendTo(parent);
_struct.set(key, el);
_struct.get(key).on({
"click": function(){
_struct.get(key).siblings().removeClass("active");
_struct.get(key).addClass("active");
}
});
});
return _struct;
};