我有一个动态生成的数组集合。我想做的是实现自动完成功能。我想通过动态获取名称并将其分配给本地数组来在单击事件处理程序中使用这些数组。但这不起作用(我不确定我的代码)。有什么办法可以实现这一点吗?
这是我的代码,我认为它应该起作用(实际上不起作用):
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script>
var ga_input1 = new Array('India','Russia','Norway');
var ga_input2 = new Array('Delhi','Mumbai','Hyderabad');
</script>
<body>
Countries: <input id="input1" type="text"/>
Cities: <input id="input2" type="text"/>
<script>
var arrayTmp = new Array();
$('input').keydown(function(){
var id = $(this).attr('id');
arrayTmp = "ga_"+id; // What I believe here is the values of ga_input1/ga_input2 are assigned to array 'arrayTmp'
//alert(arrayTmp[0]);
});
</script>
</body>
最佳答案
所有全局变量都是 window 对象的成员,因此:
arrayTmp = window["ga_"+id];
但我个人会将数据放入这样的对象中:
data = {
'input1': ['India','Russia','Norway'],
'input2': ['Delhi','Mumbai','Hyderabad']
};
...
arrayTmp = data[id];
关于javascript - 动态创建javascript数组,其名称在java脚本字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9869854/