jQuery的动态变量名

编程入门 行业动态 更新时间:2024-10-24 06:38:31
本文介绍了jQuery的动态变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

我了解的基础知识,但似乎无法找到的jQuery / JavaScript的正确的组合,使这种神奇的发生。

的jQuery('#用户列表里')。点击(函数(){    VAR用户ID = jQuery的(本).attr(ID);    //我想这个词阵列添加到用户ID的结束    VAR theVariableName =用户ID +阵列;    //我想用这个变量来创建一个数组    VAR theVariableName =新的Array();    //我要继续用在我的文档名称    theVariableName.push({的startTime:7,结束时间:10});    警报(theVariableName [0] .startTime);});

解决方案

使用一个对象来保存各种用户阵列:

window.userData = {};$(...)。点击(函数(){    // ...    window.userData [用户ID] = [];    window.userData [用户ID] .push({的startTime:7,结束时间:10});    警报(window.userData [用户ID] [0] .startTime);}

您可能不希望存储在全局命名空间中的用户数据对象虽然;以prevent意外的名称冲突,你至少应该把它放在自己的名称空间。

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

解决方案

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.

更多推荐

jQuery的动态变量名

本文发布于:2023-11-28 07:29:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641478.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量名   动态   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!