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

查看:38
本文介绍了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,所以它是 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天全站免登陆