Got a problem here and i’ve been pulling my hair last few days…
I’m making a sort of language filter function for a website and it’s a menu where you click a language and it filters out the rest of them. Since i got lots of different languages i figured it would be best to loop everything instead of making like 15 pieces of the same code.
Here’s my code:
// >>> Language click effects
for(langClickNum = 1; langClickNum < langList.length; langClickNum++) {
$('#lang'+langList[langClickNum]).click(function() {
if (!langSelect[langClickNum]) {
clrSearch();
clrLang();
langHide();
$('#lang'+langList[langClickNum]).addClass('langCheck');
$('.itemLang'+langList[langClickNum]).show();
langSelect[langClickNum] = true;
}
else {
clrLang();
langShow();
}
});
}
As you can see inside the click function I want to pick indexes from different arrays using the loop counters number. But since the script inside the click function dosent run unless I click it, it won’t catch the correct array number. Instead it picks the last array number for each language i click. I’m very aware of what problem is but I have no idea how to solve it. Please help me out there!
If I give it numbers not looping it it works just fine, like this:
$('#lang'+langList[1]).click(function() {
if (!langSelect[1]) {
clrSearch();
clrLang();
langHide();
$('#lang'+langList[1]).addClass('langCheck');
$('.itemLang'+langList[1]).show();
langSelect[1] = true;
}
else {
clrLang();
langShow();
}
});
I hope you can see my problem.
The problem is related to the concept of JS variable scoping/closure.
The value of langClickNum iterates ok when you are binding the ‘click’ handler, but when the click handler is executed, the ‘langClickNum’ is already equal to langList.length.
you could do something like:
Here, the value of langClickNum will be as you expected, because of the function scoping in JS.
see for more information:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope