开发者

JQuery select a variable by passing a text string of its name

I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

var test = "xxx";

I'm thinking I could do something like this, but it won't work:

  alert($("#test"));

Edit: People are getting confused. Think of it as a reflective way to get the contents of var test. Preferrably wi开发者_运维问答th a JQuery selector, but I'll take any way one can come up with it..


This should work for you. You have to use the variable outside the string quotes like this. You could replace the # with a . if you want to use a style selector vs an ID selector.

var test = "xxx";
alert($("#" + test));

If the field is something like <input name="xxx" .../>, you would have to use something like the following:

var test = "xxx";
alert($("[name=" + test + "]"));


Not sure what your end target is, but I use the following method a lot when I need one thing to interact with another...

<a href='whatever.html' rel='#targetElem' class='loadable'>
<script>
$(document).ready(function(){
  $('.loadable').live('click',function(){  //when a element with the class of loadable is clicked
    $($(this).attr('rel')).load($(this).attr('href')); //load the contents of it's href URL into the element specified in it's rel attribute
    return(false); // stop processing the link;
 });
});

</script>

I tell the element what the target of the action will be using the rel attribute...

to get at variables try this (window is a javascript built-in array of global variables...)

var i=2;

var test='i';
document.write('got ' + window[test]);


What you are asking is best done with JavaScript objects, e.g.:

var obj = { test: "xxx" };
for(key in obj) {
    alert(key);  // "test"  
    alert(obj.key); // "xxx"  
}

You can do something like this, though I really don't see the point:

var obj = { foo: "xxx" };
for(key in obj) {
    alert($("#" + key).length); // 1   
}

<input id="foo"/>

http://jsfiddle.net/J4hC8/


Maybe what you need is

alert($("#" + test));


var test = "#xxx";
alert($(test));

Alternatively, you can use:

var test = "xxx";
alert($("#" + test));


Not sure, but maybe you are looking for eval function.


I know this is old, but here is the solution. As stated by igor milla, you should use eval().

var test = "xxx";
alert(eval("test"));

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜