Creating a for loop to create multiple 'Click' events in JavaScript / JQuery

I want to create a For loop for a series of 'click' events on my page. I create a schedule when clicking on the "Day" button displays the events assigned to this day in the "div" field.
HTML

<div class="cwt-buttons"> <a id="cwt-button1">Monday</a> <a id="cwt-button2">Tuesday</a> <a id="cwt-button3">Wednesday</a> <a id="cwt-button4">Thursday</a> <a id="cwt-button5">Friday</a> <a id="cwt-button6">Saturday</a> <a id="cwt-button7">Sunday</a> </div> <div id="cwt-timetable"> <div class="current">Housework</div> <div class="cwt-Day1">Kickboxing</div> <div class="cwt-Day2">Homework</div> <div class="cwt-Day3">Yoga</div> <div class="cwt-Day4">Eating</div> <div class="cwt-Day5">Fasting</div> <div class="cwt-Day6">Running</div> <div class="cwt-Day7">Funeral</div> </div> 

Js

 $(function() { for ( var i = 1; i < 8; i++ ) { var clickedButton = $("#cwt-button"+i); $(clickedButton).click(function() { var currentDay = $('#cwt-timetable div.current'); var selectedDay = $('#cwt-timetable div.cwt-Day'+i); currentDay.removeClass('current').addClass('previous'); (selectedDay).css({ opacity: 0.0 }).addClass('current').animate({ opacity: 1.0 }, 1000, function() { currentDay.removeClass('previous'); }); }) } }); 

JavaScript works fine when I have an exact value, e.g. "#cwt-button1"
It just doesn't work when I concatenate the counter "i" in a loop.

Can anyone see where I'm wrong? Or am I doing something that JavaScript can't handle?

+6
source share
1 answer

This is the same old problem that is asked several times a day. All your functions created in the loop are created in the same variable area, so they have the same variable i .

To group a variable, you need a function call. jQuery $.each() is a convenient way to do this:

 $(function () { // -----------v-----scoped to the function $.each(Array(7), function(i) { var clickedButton = $('#cwt-button' + (++i)); $(clickedButton).click(function () { var currentDay = $('#cwt-timetable div.current'); // --------using scoped `i`------------------------v var selectedDay = $('#cwt-timetable div.cwt-Day' + i); currentDay.removeClass('current').addClass('previous'); (selectedDay).css({ opacity: 0.0 }).addClass('current').animate({ opacity: 1.0 }, 1000, function () { currentDay.removeClass('previous'); }); }); }); }); 
+2
source

Source: https://habr.com/ru/post/953886/


All Articles