动态jQuery变量名称

时间:2012-07-31 17:55:06

标签: javascript jquery arrays variables

我想获取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);

});

4 个答案:

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

它在这里工作:http://jsfiddle.net/bingjie2680/NnnRk/

答案 2 :(得分:0)

你可以这样做..

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

答案 3 :(得分:-2)

尝试eval

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