JQUERY programming logic

Asked

Viewed 73 times

0

Talk personal! I am not able to reason in a small problem that I am wanting to improve the code. I have several Ivs(Content1,Content2,Content3....), I have a Content check that Content is active on screen(n). By checking which n’s active, I make another div appear. So far so good, but if I have 50 contacts, I have to make 50 selection commands to check which content is active. What do you recommend so I don’t 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();
}

1 answer

1


You can put inside a loop by searching how many elements start with the id 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();
}
  • 1

    How wonderful! solved my problems! Thank you Lucas! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.