Dynamic Jquery Variable Names
I would like to take the value of an li ID attribute (which will be a userID), and use it as part of a string that I will eventually use as part of a variable name. I will use this
Solution 1:
Use an Object to hold the various user arrays:
window.userData = {};
$(...).click(function() {
// ...window.userData[userID] = [];
window.userData[userID].push({startTime:7, endTime:10});
alert(window.userData[userID][0].startTime);
}
You might not want to store the userData
object in the global namespace though; to prevent accidental name conflicts, you should at least put it in your own namespace.
Solution 2:
You can store variables in the global window
object:
jQuery('#user-list li').click(function() {
var userID = jQuery(this).attr("id");
// i want to add the word array to the end of userIDvar theVariableName = userID + "Array";
// I want to use this variable to create an arraywindow[theVariableName] = newArray();
// I want to continue to use the name throughout my documentwindow[theVariableName].push({startTime: 7, endTime: 10});
alert(window[theVariableName][0].startTime);
});
In fact every var x
declared variable x
that has not been declared in a closure will reside in the global object. However, I recommend you to use another global object, e.g. userStorageObject
or something similar:
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 userIDvar theVariableName = userID + "Array";
// I want to use this variable to create an array
userStorageObject[theVariableName] = newArray();
// I want to continue to use the name throughout my document
userStorageObject[theVariableName].push({startTime: 7, endTime: 10});
alert(userStorageObject[theVariableName][0].startTime);
});
it works here: http://jsfiddle.net/bingjie2680/NnnRk/
Baca Juga
Solution 3:
You can do that like this..
var variable = "Array";
window[id+variable] = "value";
Solution 4:
Try eval
:
var theVariableName = userID + "Array";
eval(theVariableName+"= new Array()");
Post a Comment for "Dynamic Jquery Variable Names"