So I had built a Boostrap page whereby I have an array (or list) of child nodes for selection from a dropdown menu. I wanted to detect which node had been clicked and then display the value in the new value in the menu button.
Initially I tried to detect a click event via the following code:
for (var i = 0; i < menu.length; i++){
menu[i].firstchild.innerHTML.addEventListener("click", function(){
// Assign value of node clicked on to button
button.childNodes[0].nodeValue = menu[i].firstChild.innerHTML;
});
}
However the above does not work, and menu[i].firstChild.innerHTML always seems to be undefined. I was wondering why this is the case?
I found a solution to the problem using this code from another question:
for (var i = 0; i < menu.length; i++){
(function(index) {
console.log(menu[index]);
menu[index].addEventListener("click", function(){
for (var x = 0; x < menu.length; x++){
if (menu[x] == this){
//alert(x);
//console.log(button.childNodes[0].nodeValue);
button.childNodes[0].nodeValue = menu[x].firstChild.innerHTML;
}
}
}, false);
})(i);
}
From: Detecting which node was clicked in javascript
However, I fail to really understand what is going on here. What are we actually passing into the first for loop? This seems to be (function(index){//code})(i); I can't say I have seen this syntax before. Then what is the purpose of the second for loop?
I would be very grateful if a better programmer than myself could explain to me what is going on here.
Kind Regards,