Reputation: 7128
I have a variable which contains IDs.
var mediaid = '5';
And i have a variable set
var t1 = 'First';
var t2 = 'Second';
var t3 = 'THird';
etc...
I'm trying to get variable's variable inside of jQuery's .append function.
$('#block').append('<span>{t+mediaid}</span>');
For example if mediaid is 3, {t+mediaid}
should be t3. But i have syntax errors. Can you fix it..
Upvotes: 1
Views: 265
Reputation: 146302
$('#block').append('<span>'+{t+mediaid}+'</span>');
I dont think that this is possible.
You might have to do :
$('#block').append('<span>'+window['t'+mediaid]+'</span>');
//if all those variables are in the window's scope
Better:
var mediaid = '5';
var t = ['', 'first', 'second', 'third', ...];
$('#block').append('<span>'+t[mediaid]+'</span>');
Upvotes: 3
Reputation: 27460
Try this:
$('#block').append('<span>' + eval('t'+mediaid) + '</span>');
Upvotes: -1
Reputation: 7930
Why not store your variables in an array instead of magically-named variables? Then you can access array elements by index.
var mediaid = 5;
var t = [
'Zeroth',
'First',
'Second'
// etc...
];
$('#block').append('<span>' + t[mediaid] + '</span>');
Upvotes: 1