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;
};
CodePudding user response:
What is the el
variable inside your code?
el.on({
"click": function(){
el.removeClass("active");
el.addClass("active");
}
});
You reference the variable defined on the third line (let el
). When you finish iterating the values, it will hold the last element. Every function would manipulate classes for the last value.
In a nutshell, the code adds an event listener to every element. However, the event listeners manipulate the last added element.
I suggest moving the variable definition inside the inner function block. Then you have the correct element for every click handler.
function create_struct(list, parent){
let _struct = new Map();
list.forEach((value, key, list)=>{
const 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;
};
Please let me know if it works. I might make a mistake because I can not test the code.