4

我想获取一个 li ID 属性的值(这将是一个用户 ID),并将其用作我最终将用作变量名的一部分的字符串的一部分。我将使用这个变量名来创建一个数组。

我了解基础知识,但似乎无法找到正确的 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

4 回答 4

2

使用 Object 来保存各种用户数组:

window.userData = {};

$(...).click(function() {
    // ...
    window.userData[userID] = [];
    window.userData[userID].push({startTime:7, endTime:10});

    alert(window.userData[userID][0].startTime);
}

不过,您可能不想将userData对象存储在全局命名空间中;为了防止意外的名称冲突,您至少应该将它放在您自己的命名空间中。

于 2012-07-31T18:03:26.443 回答
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/

于 2012-07-31T18:01:37.507 回答
0

你可以这样做..

var variable = "Array";
window[id+variable] = "value";
于 2012-07-31T18:02:13.160 回答
-2

尝试eval

var theVariableName = userID + "Array";
eval(theVariableName+"= new Array()");
于 2012-07-31T18:03:48.957 回答