如何使用jQuery创建动态变量? [英] How to create dynamic variables using jquery?
问题描述
我希望动态创建一些jquery变量.在我的代码中,我有一个循环,并且要使用循环值创建一些变量.这是我的示例代码.
I want some jquery variables to be created dynamically. In my code I am having a loop, and with the loop values I want to create some variables. Here is my sample code.
array=["student","parent","employee"]
$.each(user_types, function( index, value ){
var value+"_type" // this is the type of variable i want to build.
})
我发现了有关 eval 函数的信息.该代码是这样的.
I have found about eval function. That code goes like this.
var type = "type"
eval("var pre_"+type+"= 'The value of dynamic variable, val';");
alert(pre_type) // this gives 'The value of dynamic variable, val' in alert box.
是否有其他替代方法,因为我在编码 .js 文件时不喜欢使用eval函数.
Is there any alternate ways as I have read the eval function is not prefered while coding .js files.
推荐答案
每当您发现自己以变量名使用变量时,您可能都想使用对象文字.用大括号{}
创建对象,然后使用方括号表示法设置对象属性键:
Any time you find yourself using a variable in the name of a variable, you probably want to use an object literal. Create the object with curly braces {}
, and then set the object property key using square bracket notation:
var user_types = ["student","parent","employee"];
var types = {};
$.each(user_types, function( index, value ){
types[value] = 'The value of dynamic variable, val';
});
注意:您尚未对其进行标记,但是我想是因为您已经使用each()
来使用jQuery,所以如果我错了,请更正我.
Note: You haven't tagged it, but I assume because you've used each()
that you are using jQuery, please correct me if I'm wrong.
这篇关于如何使用jQuery创建动态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!