我想动态创建一些jquery变量。在我的代码中,我有一个循环,并且要使用循环值创建一些变量。这是我的示例代码。
array=["student","parent","employee"]
$.each(user_types, function( index, value ){
var value+"_type" // this is the type of variable i want to build.
})
我发现了有关评估功能。该代码是这样的。
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函数。
每当您发现自己以变量名使用变量时,您可能都想使用对象文字。用花括号创建对象{}
,然后使用方括号表示法设置对象属性键:
var user_types = ["student","parent","employee"];
var types = {};
$.each(user_types, function( index, value ){
types[value] = 'The value of dynamic variable, val';
});
注意:您尚未对其进行标记,但是我想是因为您each()
使用过jQuery,因此如果我错了,请更正我。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句