Dynamic jQuery variable names

空扰寡人 提交于 2020-01-03 17:31:11

问题


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 variable name to create an array with.

I understand the basics, but can't seem to find the right combination of jQuery/javascript to make this magic happen.

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);

});

回答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.




回答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 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);
});

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 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);
});

it works here: http://jsfiddle.net/bingjie2680/NnnRk/




回答3:


You can do that like this..

var variable = "Array";
window[id+variable] = "value";



回答4:


Try eval:

var theVariableName = userID + "Array";
eval(theVariableName+"= new Array()");


来源:https://stackoverflow.com/questions/11746155/dynamic-jquery-variable-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!