开发者

Javascript - How do I declare a variable with the variable name based on a string?

开发者 https://www.devze.com 2023-01-15 19:16 出处:网络
var cur_storage_unit = $(\'#storage_unit\').val(); $(\'.size_unit\').change(function() { var id 开发者_JAVA百科= $(this).attr(\'id\');
var cur_storage_unit = $('#storage_unit').val();

$('.size_unit').change(function() {
    var id 开发者_JAVA百科= $(this).attr('id');

    //This is how I want it to work, but not sure how
    'cur_' + id = $(this).val();
});

The user 'changes' a of class 'size_unit' and id of 'storage_unit'. I want to then set the value of 'cur_storage_unit' to the new value of 'storage_unit'. In italics is how I want it to work, but I'm not sure the syntax of how to get it to work. Thanks!


You're probably better off using an Object, and storing it in there.

var cur_storage_unit = $('#storage_unit').val();

var values = {};  // storage for multiple values

$('.size_unit').change(function() {
    var id = this.id;

    values['cur_' + id] = this.value;  // store this value in the "values" object
});

// Accessible via values object
alert( values["cur_theid"] );


you can create a new property on an object using a string as a key

var myObj = {};
myObj['cur_'+id] = $(this).val();

so in your case you would want an object with a known name where you can add dynamically named properties.


If it's global you can do window['cur_'+id];

0

精彩评论

暂无评论...
验证码 换一张
取 消