Faced a problem (question).
I have a fairly simple action when I click on an element:

$(document).on('click', '.add-plus-btn.transition_1', function() { $(this).fadeOut(0); $('.add-transition.transition_1').fadeIn(250); }); $(document).on('click', '.add-plus-btn.transition_2', function() { $(this).fadeOut(0); $('.add-transition.transition_2').fadeIn(250); }); // И так до transition_60 элементов (может быть по разному); 

How can I simplify the code, maybe with a for loop? But it does not work ...
Thank!

  • transfer this class to the date attribute and make one handler - Grundy
  • Why cycle if you can hang the handler on .add-plus-btn and use this inside? True strange somehow fadeOut and immediately fadeIn on the same element - Alexey Shimansky
  • @ Alexey Shimansky, how will you determine which of the transition_* classes is present for this, if it has several of them - Grundy
  • @ Alexey Shimansky are different elements - Igor
  • @Igor clear. I see. - Alexey Shimansky

1 answer 1

 var clickHandlerProvider = function(index) { return function() { $(this).fadeOut(0); $('.add-transition.transition_' + index).fadeIn(250); }; } for (var iter = 1; iter <= 2; iter++) { $(document).on('click', '.add-plus-btn.transition_' + iter, clickHandlerProvider(iter)); } 
  • Everything works great! Thank!! - Vasily UK