开发者

Convert string to variable in Javascript

Is there any way to convert a string to a variable in Javascript? Right now, what I have is a script that updates data based on the values of the select box:

<script type="text/javascript">
var a = new Array();
a[0] = 'Name';
a[1] = 'Description';

var b = new Array();
b[0] = 'Name 2';
开发者_运维问答b[1] = 'Description 2';

function changeSystem(){
    var selectedAccount=document.getElementById('selected_option').value;

    document.getElementById('name').innerHTML = selectedAccount[0];
    document.getElementById('description').innerHTML = selectedAccount[1];
}
</script>
<form method="POST">
    <select onchange="changeSystem()" id="selected_option">
     <option>A</option>
     <option>B</option>
    </select>
</form>
<span id="name"></span><br>
<span id="description"></span><br>

selectedAccount is the string of the chosen element in <select>. However, for it to access the array, it needs to be a variable, i.e. a[0] instead of 'a'[0]. What solutions are there to this?


var dict = {
    'A': ['Name', 'Description'],
    'B': ['Name 2', 'Description']
};

dict['A'][0]

So dynamically access it with

dict[selectedAccount][0]

You can use an object literal instead of an array:

var dict = {
    'A': {'name': 'john'}
};

dict['A']['name']


I would use something like that:

<script type="text/javascript">
var stuff = { 
    A: { name: 'Name', desc: 'Description'},
    B: { name: 'Name 2', desc: 'Description 2'}
};

function $(aId) {
    return document.getElementById(aId);
}

function changeSystem(){
    var selectedAccount = $('selected_option').value;

    if (selectedAccount in stuff) {
        $('name').innerHTML = stuff[selectedAccount].name;
        $('description').innerHTML = stuff[selectedAccount].desc;
    } else {
        $('name').innerHTML = '';
        $('description').innerHTML = '';
    } 
}
</script>
<form method="POST">
    <select onchange="changeSystem()" id="selected_option">
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>
</form>
<span id="name"></span><br>
<span id="description"></span><br>

Tested on: Google Chrome 6.0.427.0 dev

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜