动态jQuery变量名
Dynamic jQuery variable names
我想获取li-ID属性的值(它将是一个userID),并将其用作字符串的一部分,最终用作变量名的一部分。我将使用这个变量名创建一个具有的数组。
我了解基本知识,但似乎找不到jQuery/javascript的正确组合来实现这一神奇功能。
jQuery('#user-list li').click(function() {
var userID = jQuery(this).attr("id");
// i want to add the word array to the end of userID
var theVariableName = userID + "Array";
// I want to use this variable to create an array
var theVariableName = new Array();
// I want to continue to use the name throughout my document
theVariableName.push({startTime: 7, endTime: 10});
alert(theVariableName[0].startTime);
});
使用对象来保存各种用户数组:
window.userData = {};
$(...).click(function() {
// ...
window.userData[userID] = [];
window.userData[userID].push({startTime:7, endTime:10});
alert(window.userData[userID][0].startTime);
}
不过,您可能不想将userData
对象存储在全局命名空间中;为了防止意外的名称冲突,您至少应该将其放在自己的命名空间中。
您可以将变量存储在全局window
对象中:
jQuery('#user-list li').click(function() {
var userID = jQuery(this).attr("id");
// i want to add the word array to the end of userID
var theVariableName = userID + "Array";
// I want to use this variable to create an array
window[theVariableName] = new Array();
// I want to continue to use the name throughout my document
window[theVariableName].push({startTime: 7, endTime: 10});
alert(window[theVariableName][0].startTime);
});
事实上,每个未在闭包中声明的var x
声明变量x
都将驻留在全局对象中。但是,我建议您使用另一个全局对象,例如userStorageObject
或类似的对象:
var userStorageObject = {};
jQuery('#user-list li').click(function() {
var userID = jQuery(this).attr("id");
// i want to add the word array to the end of userID
var theVariableName = userID + "Array";
// I want to use this variable to create an array
userStorageObject[theVariableName] = new Array();
// I want to continue to use the name throughout my document
userStorageObject[theVariableName].push({startTime: 7, endTime: 10});
alert(userStorageObject[theVariableName][0].startTime);
});
它在这里工作:http://jsfiddle.net/bingjie2680/NnnRk/
你可以这样做。。
var variable = "Array";
window[id+variable] = "value";
尝试eval
:
var theVariableName = userID + "Array";
eval(theVariableName+"= new Array()");
相关文章:
- 如何使用jQuery循环变量名
- 检索本身包含变量的 Jquery 变量名的值
- 动态jQuery变量名
- jquery没有't从DIV数据id中获取PHP变量值,只输出变量名
- Ajax jquery post发布时没有变量名
- 在jquery data()对象上循环,并将值写入以键为变量名的变量中
- JQuery组合变量名
- jQuery从变量名检查类
- JS - 运行带有变量名的 jQuery 函数
- 如何将变量名转换为对象jQuery的索引字符串
- $issue作为前缀jquery变量名
- jQuery在for循环中动态递增变量名
- 在jquery中使用增量变量名从json中获取值
- 将字符串转换为要在jQuery.animate中使用的变量名
- Jquery selectbox删除所有选项,除了两个(选择器变量名)
- 调用名为变量的jQuery方法
- 我们可以在html中有变量名,jQuery
- Jquery显示变量名而不是值
- 基于变量名调用jQuery自动完成小部件函数
- 使用jquery从select元素中选择变量名