Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

jquery - Convert a string to a variable name in javascript?

Ok you have a set of variables:

var height1 = 10
var height2 = 20
...
var height7 = 70;

The user has given input and you need to get the value of one of those variables, here's the code for that:

if(window.location.hash) {
      var hash = window.location.hash.substring(1); 
            var option_name = $('a[name=' + hash + ']').closest('[id^="option"]').attr("id");
            var hash_div_height_id = "height" + option_name.substring(6);
            $('a[name=' + hash + ']').closest('[id^="option"]').show();
            $('a[name=' + hash + ']').closest('[id^="option"]').height(hash_div_height_id);
  } else {
      // No hash found
  }

My problem now being that I can't pass "hash_div_height_id"(which would currently represent the string "height1" or "height2" or whatever number the jQuery returned to append to the end of the string) to the height function as it's a string.

So how can I go about this? Can I somehow convert the string "height1" to represent the variable height1 that was established earlier?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assign the height's as properties of an object.

Something like..

var heightObj = {
        height1 : 10,
        height2 : 20,
        height7 : 70
    };

var hash_div_height_id = "height" + option_name.substring(6);

To access the particular property , use the [] notation to access the property

var newHeight = heightObj[hash_div_height_id];
$('a[name=' + hash + ']').closest('[id^="option"]').height(newHeight);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...