javascript variable usage help
Ok guys here's my dilemma, I just need some basic help... soo
if I have a set of variable say...
$h1 = ""
$h2 = ""
$h3 = ""
$h4 = ""
and i'm using a data attribute on the element, how can I use the number I pull to put into a string that acts as the variable name. so in the function below, you click a class item, it get's the value from the data attribute then I need to populate the #work_hold div with the corresponding variable. If I do what I have below, the $tme acts as开发者_Go百科 a string and doesnt work. any ideas?
$(".box").click(function(){
var atr = $(this).attr("data-bsel");
$tme = '$h'+atr;
$('#work_hold').html($tme);
});
You want an array:
var h = [];
h[0] = ...;
h[1] = ...;
h[2] = ...;
...
$tme = h[atr];
You do NOT want to build variables dynamically. That just leads to utterly icomprehensible and impossible to debug code.
use javascript objects:
var nameSpace = {"$h1": 109};
$(".box").click(function(){
var atr = $(this).attr("data-bsel");
$tme = nameSpace['$h'+atr];
$('#work_hold').html($tme);
});
精彩评论