我想获取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);
});
答案 0 :(得分:2)
使用Object来保存各种用户数组:
window.userData = {};
$(...).click(function() {
// ...
window.userData[userID] = [];
window.userData[userID].push({startTime:7, endTime:10});
alert(window.userData[userID][0].startTime);
}
您可能不希望将userData
对象存储在全局命名空间中;为了防止意外的名称冲突,你至少应该将它放在你自己的命名空间中。
答案 1 :(得分:1)
您可以将变量存储在全局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);
});
答案 2 :(得分:0)
你可以这样做..
var variable = "Array";
window[id+variable] = "value";
答案 3 :(得分:-2)
尝试eval
:
var theVariableName = userID + "Array";
eval(theVariableName+"= new Array()");