Several functions in the document.ready function

here is my code:

$(document).ready(function () {

    $('.flip1').click(function () {
        $('.panel1').slideToggle("slow");
    });
    $('.flip2').click(function () {
        $('.panel2').slideToggle("slow");
    });
    $('.flip3').click(function () {
        $('.panel3').slideToggle("slow");
    });
    $('.flip4').click(function () {
        $('.panel4').slideToggle("slow");
    });
});

I want to create a loop with .flip as a variable (flipVar) and .panel as (panelVar)

+3
source share
4 answers

Even if you want to run the selector in a loop, I would not do it this way because you are making several DOM variants. You can do this with a single DOM selection:

$(document).ready(function () {
    $('div[class^=flip]').each(function ( idx ) {
        $(this).click(function() {
            $('.panel' + (idx + 1)).slideToggle("slow");
        });
    });
});

This will work assuming the elements flipappear on the page in their numerical order.

, <div>, , "flip". , , , .

index, .each() , .panel.

+3

, , , , . :

 for (var i = 1; i <= 4; ++i) $('.flip' + i).click((function(i) {
   return function() { $('.panel' + i).slideToggle('slow'); };
 })(i));

, "click" . , . , "flip" , ( "" ) "data-". , .

edit — , , "somethingNN", "NN" . , "":

for (var i = 1; i <= 4; ++i) $('.flip' + i).click(function() {
  var panelClass = this.className.replace(/.*\bflip(\d+).*/, "panel$1");
  $(panelClass).slideToggle('slow');
});
+4
$(document).ready(function () {

    for (var i=1; i<=4; i++) {
       (function(i) {
          $('.flip'+i).click(function () {
             $('.panel'+i).slideToggle("slow");
          });
       })(i);
    }

}); 
+1

:

$(function(){
    for(var i=1;i<5;i++){
         $('.flip'+i).click(function () {
             $('.panel'+i).slideToggle("slow");
         });
    }
});

PS: - , , @patrick

0
source

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


All Articles