programming logic JQUERY

0

Speak up! I am not able to reason in a problem that I am trying to improve the code. I have several divs (Content1, Content2, Content3 ....), I have a function that checks what content is active on the screen (n). By checking which asset is active, I make another div appear. so far so good, but if I have 50 contents, I have to make 50 selection commands to check which content is active. What do you recommend not to use so many selection commands? THANK YOU VERY MUCH.

HTML:

<div class="content-switcher" id="Content1">
<div class="imagemblock" style="display:none;"></div>
</div>
<div class="content-switcher" id="Content2">
<div class="imagemblock" style="display:none;"></div>
</div>
<div class="content-switcher" id="Content3">
<div class="imagemblock" style="display:none;"></div>
</div>

JQUERY:

 function selectStep(n) { 
//A MAGIA ESTA AQUI. NÃO GOSTARIA DE FAZER TANTOS "IFS".
if(n==1){
     $('#Content1 .imagemblock').fadeIn().show();
}
if(n==2){
     $('#Content2 .imagemblock').fadeIn().show();
}
if(n==3){
     $('#Content3 .imagemblock').fadeIn().show();
}
//OS CONTENTS SÃO MUDADOS COM OUTRO TREXO DE CODIGO DE ONCLICK.
 $(".content-switcher").hide();
    $("#Content" + n).show();
}
    
asked by anonymous 25.01.2017 / 12:29

1 answer

1

You can put inside a loop by searching for how many elements begin with% content: :

function selectStep(n) {
    // obtem a qtd de elementos na tela que começa com Content
    var size = $("div[id^='Content']").length;
    for (var i = 1; i <= size; i++) {
        if (n == i) {
            $('#Content' + n + ' .imagemblock').fadeIn().show();
        }
    }
    //OS CONTENTS SÃO MUDADOS COM OUTRO TREXO DE CODIGO DE ONCLICK.
    $(".content-switcher").hide();
    $("#Content" + n).show();
}
    
25.01.2017 / 12:37