Solution uses const
, an ES6 feature. The benefits are that selector
s scope is confined to the for loop and that the variable identifier cannot be reassigned.
Depending on your desired browser compatibility it may or may not be available.
As @IcePickle pointed out, using var
in the for...in
loop would mean that selector
is always .may
in the click handlers due to var
having different socping rules. See Creating closures in loops - A common mistake for a detailed explanation.
Using var
and another closure:
var selectorToReponse = {
'.ottogi': 'Ottogi',
'.sajo': 'Sajo Hapyo',
'.natura': 'Natura Bogata',
'.maloo': 'TOO Maлy',
'.dongush': 'Dongsuh',
'.may': 'OOO Maй'
}
var $header = $('.inner-container h1')
for (var selector in selectorToResponse) {
$(selector).click = (function (selector) {
return function () {
if ($header.text() === 'Ottogi') {
var response = selectorToResponse[selector]
$header.text(response)
}
}
})(selector)
}