动态变量在javascript中命名 [英] Dynamic variables names in javascript
问题描述
我有变量:
var variableDynamic = 1;
// or
var variableDynamic = 1 + i++;
有没有办法用它来创建动态变量名,例如:
Is there any way to use that to create dynamic variable names, for example something like this:
var variableName + variableDynamic = {};
// or
var (variableName + variableDynamic) = {};
我知道上面写的是荒谬的,但这是为了解释这个想法。有可能吗?
I know what I wrote above is absurd, but this is to explain the idea. Is it possible?
好的,每次用户点击添加时我想要创建元素(上传表单)新的文件组,一切正常,除了我用它的插件需要特殊的变量为每个上传表单触发上传按钮(.uploadStoredFiles();)。
Ok, what I want to do to create element (upload form) every time user click on add new file group, everything is working fine except that plugin that I use for it need special variable for each upload form to trigger upload button (.uploadStoredFiles();).
这是我做的粗略代码:
$('#addOneMoreFileOrGroup').on('click', function(){
var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;
$('.well-large .control-group:last').after('<div class="control-group deal-type-online"> \
<label class="control-label">File / File Group Title:</label> \
<div class="controls"> \
<input class="span4 file-title" type="text"> \
<span class="question label label-warning" data-title="File / Group Name:" data-content="Name for your file or group of related files (for example your brand logotype in different file formats)." data-original-title="">?</span> \
<div id="file-uploader-' + latestFileUploaderId + '" class="file-uploader"></div> \
</div> \
</div>');
var HERE_I_NEED_DYNAMIC_VAR = new qq.FileUploader({
element: document.getElementById('file-uploader-' + latestFileUploaderId + ''),
action: 'do-nothing.htm',
autoUpload: false,
debug: true,
uploadButtonText: '<i class="icon icon-plus"></i> Select Files...',
onSubmit: function() {
$('#file-uploader-' + latestFileUploaderId + ' .qq-uploader').after('<button id="file-uploader-trigger-' + latestFileUploaderId + '" class="btn btn-primary"><i class="icon-upload icon-white"></i> Upload now</button>');
$('#file-uploader-trigger-' + latestFileUploaderId + '').on('click', function() {
if($(this).parent().parent().parent().parent().find('.file-title').val() !== '') {
HERE_I_NEED_DYNAMIC_VAR.uploadStoredFiles();
} else {
$(this).parent().parent().parent().addClass('error');
}
});
}
});
});
}
推荐答案
在JavaScript中,对象的属性可以通过 obj.prop
或 obj ['prop']
进行访问。
In JavaScript, an object's properties can be access either by obj.prop
or obj['prop']
.
在全局范围内,所有变量都是窗口
属性的子项。所以你将能够做到:
In the global scope, all variables are children of the window
property. So you'll be able to do:
var variableDynamic = 'Test';
window['variableName' + variableDynamic] = 'your value';
查看这个小提琴。
但是,如果你想将这个变量的范围限制为一个函数,你必须定义一个父对象并使用它来代替窗口
。
However, if you'd like to limit the scope of this variable to a function, you would have to define a parent object and use this in place of window
.
这篇关于动态变量在javascript中命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!