JavaScript Dynamic Variable Names

前端 未结 6 842
感动是毒
感动是毒 2020-11-27 21:23

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

6条回答
  •  野性不改
    2020-11-27 21:35

    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] = '

    Hello World

    '; }); alert( vars['hello1'] );

    FIDDLE

提交回复
热议问题