Pergunta

I'm new to programming and trying to simplify some jquery/javascript code but I'm not having much success. I tried to adapt the solution found here: jQuery Simplify

...but again, no success.

Here's my jquery code:

<script>
$(document).ready(function(){

$("#hide01").click(function(){
$(".content01").hide();
});

$("#show01").click(function(){
$("p").hide();
$(".content01").show();
});

$("#hide02").click(function(){
$(".content02").hide();
});

$("#show02").click(function(){
$("p").hide();
$(".content02").show();
});

});
</script>

And the HTML:

<button id="hide01">Hide</button>
<button id="show01">Show</button>

<button id="hide02">Hide</button>
<button id="show02">Show</button>

<p class="content01">Content 01</p>

<p class="content02">Content 02</p>

This solution is working but I need something like 40 buttons / blocks of content...

Anyone can help? Thanks!

Foi útil?

Solução

I would change the HTML to this:

<button class="btn_hide" data-id="01">Hide</button>
<button class="btn_show" data-id="01">Show</button>

<button class="btn_hide" data-id="02">Hide</button>
<button class="btn_show" data-id="02">Show</button>

<p id="content01">Content 01</p>
<p id="content02">Content 02</p>

Then your jQuery can be:

$(".btn_hide").click(function() {
    $("#content"+this.getAttribute("data-id")).hide();
});
$(".btn_show").click(function() {
    $("p").hide();
    $("#content"+this.getAttribute("data-id")).show();
});

Outras dicas

Well with jQuery you can stack selectors IE:

 $("#hide01, #show01").click(function(){
    $(".content01").hide();
 });

But personally i would, rather than using ID's, use a class for this:

  <button id="hide01" class="hide">Hide</button>
  <button id="show01" class="show">Show</button>
  <button id="hide02" class="hide">Hide</button>
  <button id="show02" class="show">Show</button>
  <button id="hide03" class="hide">Hide</button>
  <button id="show04" class="show">Show</button>

JS

 $(".hide").click(function(){
    $(".content01").hide();
 });
 //Etc Etc..
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top