views:

29

answers:

2

I have a variable whose value is the same as an ID on the page. When I do this:

var foo = 'value';
$('#' + foo).thing();

it doesn't work. But this does work:

var foo = 'value';
var bar = '#' + foo; //'#value';
$(bar).thing();

How can I build that selector in a single line? Creating extra single-use variables seems wasteful.

A: 

Hmmm. I've never had the problem. But perhaps you can try just adding another set of brackets around your inner statement:

$(("#" + foo)).something();

If im not offtrack, this might force javascript to "calculate" the inner brackets first, before passing it into the jQuery selector function. Goog luck...

joshuafreelance
Nope...actually I just tested it and it works fine to dynamically gen a selector string. Make sure you declared the variable holding your selector string cause if you use the wrong name, JavaScript will just create a new empty string and try to use this as the intended variable, which would obviously fail. If you copy the your code, I'll have a look...
joshuafreelance
+1  A: 

User error -- I had an '@' in the variables (working on a Twitter thing), so the resulting ID was '#@value' which is illegal because of the @. Fixed that, and it's working now.

Martin McClellan