在 Javascript 中将字符串转换为变量
Javascript 有没有办法将字符串转换为变量?现在,我拥有的是一个根据选择框的值更新数据的脚本:
<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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
动态访问它:
因此,可以使用对象文字而不是数组来
So dynamically access it with
You can use an object literal instead of an array:
我会使用类似的东西:
测试:Google Chrome 6.0.427.0 dev
I would use something like that:
Tested on: Google Chrome 6.0.427.0 dev