JavaScript动态变量名称 [英] JavaScript Dynamic Variable Names

查看:309
本文介绍了JavaScript动态变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我想创建变量,因为用户点击后每次点击都会添加一个新变量。我目前正在使用jquery和javascript我无法在服务器端执行此操作必须在浏览器中完成。

Ok so I want to create variables as a user clicks threw the code every click adds a new variable. I am currently using jquery and javascript I can't do it server side this must be done in the browser.

newCount = document.getElementById('hello').innerHTML;
    $('.hello').click(function(){
        //set count fast enumeration
        newCount++;
        var hello + newCount = '<p>Hello World</p>';
    }); 

所以我希望变量为hello1,hello2,hello3,hello4等。

so I want the variables to be hello1, hello2, hello3, hello4, etc.

推荐答案

您只能使用括号表示法,这意味着您必须将变量附加到某些内容。

全局范围将是窗口,因此它将是 window ['hello'+ newCount] ,但是用一堆随机属性污染全局命名空间听起来不是一个好主意,所以使用对象似乎更好

You can only do that with bracket notation, which means you have to attach the variables to something.
The global scope would be window, so that would be window['hello' + newCount], but polluting the global namespace with a bunch of random properties doesn't sound like a good idea, so using an object seems better

var vars = {};
var newCount = parseInt($('#hello').html(), 10);

$('.hello').click(function(){
    newCount++;
    vars['hello' + newCount] = '<p>Hello World</p>';
}); 

alert( vars['hello1'] );

FIDDLE

这篇关于JavaScript动态变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆