Pregunta

I was thinking u guys might be able to help.

I now have hundreds of lines of code like the below for each entry. What started as a little stream1 and so on, turned into a mess in my file.

So the code goes from streamtitle1 all the way to streamtitle30 now. The only thing that changes is the

       $("#streamtitleXX").click(function(){
       $("#streamXX").show();
       and all other hide.

This is an example of entry 23. PLEASE HELP WITH AN EFFICIENT "WHATEVER" LOOP. I WILL GIVE YOU A SHOUT OUT ON MY PAGE.

$("#streamtitle23").click(function(){
$("#stream0").hide();
$("#stream23").show();
$("#stream1").hide();
$("#stream2").hide();
$("#stream3").hide();
$("#stream4").hide();
$("#stream5").hide();
$("#stream6").hide();
$("#stream7").hide();
$("#stream8").hide();
$("#stream9").hide();
$("#stream11").hide();
$("#stream10").hide();
$("#stream12").hide();
$("#stream13").hide();
$("#stream14").hide();
$("#stream15").hide();
$("#stream16").hide();
$("#stream17").hide();
$("#stream18").hide();
$("#stream19").hide();
$("#stream20").hide();
$("#stream21").hide();
$("#stream22").hide();
$("#stream23").hide();
$("#stream24").hide();
$("#stream25").hide();
$("#stream26").hide();
$("#stream27").hide();
});

THANKS

¿Fue útil?

Solución

DEMO

$("[id^=streamtitle]").on('click', function () {
    $("[id^=stream]:not([id^=streamtitle])").hide();
    var num = $(this).attr('id').replace('streamtitle','');
    $("#stream"+num).show();
});

...but I still say that a common class is the way to go.

Otros consejos

var XX = 23;
for (var i=1; i <= 27; i++){
    if (i !== XX){
        $('#stream'+i.toString()).hide();
    } else {
        $('#stream'+i.toString()).show();
    }
}

If you can have same class for all the stream elements/divs then you can hide them all with hide() and show only the one you want to as shown below

$("#streamtitleXX").click(function(){ $(".streamClass").hide(); $("#streamXX").show();});

Hope this helps

I'd give all your stream titles a streamtitle class and all your streams a stream class.

Then do something like this.

$('.streamtitle').click(function() {
  $('.stream').hide();
  $('#stream' + this.id.replace(/streamtitle/, '')).show();
});

Demo http://jsfiddle.net/mg2kF/

$("[id^='streamtitle']").click(function(){
var shid='stream'+$(this).attr('id').replace('streamtitle','');
$('[id^="stream"]').hide();$('#'+shid).show();
});
** HTML **

<div title="Stream Title" id="streamtitle23" onclick="showChildStream('23');"></div>
<div title="Stream Title" id="streamtitle24" onclick="showChildStream('24');"></div>
<div title="Stream Title" id="streamtitle25" onclick="showChildStream('25');"></div>

** Jquery **

function showChildStream(currentid)
{
$("#stream"+currentid).show();
 for(var i=0;i<28;i++){
if(i!=currentid)
     $("#stream"+i).hide();
 }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top