Use id to call variable in jQuery

I have about 40 samples with an identifier. After clicking on the sample, the image should change and the text inside the image will also change. I'm currently grabbing the id and using it to add to the image url like this:

$('.swatches').children('img').click(function(){
    var clickedId = $(this).attr("id");

    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId');
  })

Tant works great!

Also, inside my script, I have all the text stored as variables, for example:

var firstText = "Text for the first image",
    secondText = "Some other kind of text",
    thirdText = "Yet more text that really different from the other two";

The identifier matches the variable when “Text” is added to it, so I assumed that I could just do something like:

$('.swatches').children('img').click(function(){
    var clickedId = $(this).attr("id");
    var newText = clickedId + "Text"

    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId);
    $('#imageText').html(newText);

  })

I assumed that in this case, "newText" will refer to global variables ("firstText", "secondText", "thirdText", etc.). But without cubes.

? - ( "newText" ) , .

+4
1

, javascript-, :

var imageTexts = {};
imageTexts['first'] = "Text for the first image";
imageTexts['second'] = "Some other kind of text";
imageTexts['third'] = "Yet more text that really different from the other two";

jQuery :

$('.swatches').children('img').click(function(){
    var clickedId = $(this).attr("id");
    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId);
    // Reference "imageTexts" with the clickedID (assuming 'first', 'second', etc)
    $('#imageText').html(imageTexts[clickedId]);

  })
+3

All Articles