开发者

Javascript Variables Variable (Syntax Error)

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+me开发者_运维百科diaid} should be t3. But i have syntax errors. Can you fix it..


$('#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>');


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>');


Try this:

$('#block').append('<span>' + eval('t'+mediaid) + '</span>');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜