I have a little problem with one of my javascript code. Here is the code
//assume array is an array containing strings and myDiv, some div in my doc
for(var i in array) {
var myString = array[i];
var a = document.createElement('a');
a.innerHTML = myString;
a.addEventListener("click", function() {myFunc(myString)}, false);
myDiv.appendChild(a)
}
function myFunc(s) {alert(s);}
However, since Strings are passed by reference in JavaScript, I see always the last string of my array when I click on the link a in question. Thus, my question is "How can I pass myString by value ?". Thank you for your help !
Phil
You should add a closure around your event handler:
JavaScript closure inside loops – simple practical example
a.addEventListener("click", function (s) {
return function () {
alert(s)
};
}(myString), false);
Also, you should not use for...in loops on arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With