I have been puzzling for several hours, I can not understand why my code is not working correctly. In general, my goal is that when you click on the main page, the text inside the <h1> tag changes
Earlier, I did it in a simple way as shown below, and of course I registered each class of the .ottogi .sojo .natura well, and so on. You can refer to the following link http://test1.testkz.ru/
var text = $('.inner-container h1').text(); var changeString = $('.inner-container h1'); $('.ottogi').click(function() { if (text == 'Ottogi') { $(changeString).text('Ottogi'); } }); $('.sajo').click(function() { if (text == 'Ottogi') { $(changeString).text('Sajo Hapyo'); } }); Then, in order not to repeat this procedure 6 times, I decided to create an object, and run through it with a for ... in loop to implement this procedure. Maybe my if does not work correctly. Guys look and help please
const selectorToResponse = { '.ottogi': 'Ottogi', '.sajo': 'Sajo Hapyo', '.natura': 'Natura Bogata', '.maloo': 'TOO Maлy', '.dongush': 'Dongsuh', '.may': 'OOO Maй' } // Prefixing with $ to denote that is an element, not text etc const $header = $('.inner-container h1') for (const selector in selectorToResponse) { $(selector).click = function () { // using $header.text() inside function so that is current header text // `text` never changed in your example if ($header.text() === 'Ottogi') { // using === instead of == const response = selectorToResponse[selector] $header.text(response) } } } Here is the HTML
<div class="left-main col-lg-3 col-md-3 col-sm-12 col-xs-12"> <div class="shadow-effect"><p class="ottogi">OTTOGI</p></div> <div class="shadow-effect"><p class="sajo">Sajo Hapyo</p></div> <div class="shadow-effect"><p class="natura">Natura Bogata</p></div> <div class="shadow-effect"><p class="maloo">ТОО Малу</p></div> <div class="shadow-effect"><p class="dongush">Dongsuh</p></div> <div class="shadow-effect"><p class="may">ООО Май</p></div> </div> <div class="right-main col-lg-9 col-md-9 col-sm-12 col-xs-12"> <div class="inner-container"> <h1>Ottogi</h1> <h2>Южно - Корейские продукты питания высочайшего качества!</h2> </div> 