动态jQuery变量名

Dynamic jQuery variable names

本文关键字:变量名 jQuery 动态      更新时间:2023-09-26

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

使用对象来保存各种用户数组:

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

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

您可以将变量存储在全局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/

你可以这样做。。

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

尝试eval:

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