-1

This all seems to work great just the really strange thing is when I try to reference the var with .html('g'+index) it throws an object expected error. I guessing building the var isn't the best thing?

var g0 = "<?php getFiles("gallery/Audience"); ?>";
var g1 = "<?php getFiles("gallery/Exhibition"); ?>";
var g2 = "<?php getFiles("gallery/registration"); ?>";
var g3 = "<?php getFiles("gallery/Speakers"); ?>";

$(".galleryButton").each(function (index) {
    $(this).click(function(){
        $('#galleria').html();                              
        $('#galleria').html('g'+index);
        initiateGallery();
    }).mouseover(function() {
        $(this).css('cursor', 'pointer');
        $(this).css('backgroundColor', '#002E53');
    }).mouseout(function(){
        $(this).css('backgroundColor', '#000');
    });
});

3 Answers3

1

You could use eval to get the value of the variable gx.

$(this).click(function(){
    $('#galleria').html();                              
    $('#galleria').html(eval('g'+index));
    initiateGallery();
})

But as eval is evil you should use a switch-case to get the variables:

$(this).click(function(){
    $('#galleria').html();
    var contents;
    switch(index) {
        case 1:
            contents = g1;
            break;
        case 2:
            contents = g2;
        ...
    }
    $('#galleria').html(contents);
    initiateGallery();
})

I guess that you're trying to clear the html of #galleria with this line:

$('#galleria').html();

You should pass an empty string to html() to clear the content:

$('#galleria').html('');
Oscar
  • 766
  • 1
  • 6
  • 13
  • I agree with your solution, but I don't think `eval` is the devil in every case, it should be used wisely that's all. – Michael Laffargue Mar 24 '11 at 10:41
  • I agree that there are situations where eval is the best alternative. But most of the uses of eval that I see are not cases where eval is used wisely. – Oscar Mar 24 '11 at 10:44
  • Ahhhh yes was trying to clear the html but always miss the ('') thats working better... – MarkBeharrell Mar 24 '11 at 11:30
  • Worked perfectly! Why is 'eval' evil? – MarkBeharrell Mar 24 '11 at 11:34
  • There are many opinions about this but I think that [this question](http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil/198031#198031) explains it quite good – Oscar Mar 24 '11 at 12:37
0

If you are wanting to insert the text string 'g'+index into the HTML then I would probably suggest doing...

$('#galleria').html('<span>g'+index+'</span>');
El Ronnoco
  • 11,753
  • 5
  • 38
  • 65
0

You should use the evalmethod : $('#galleria').html(eval('g'+index));

Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76