javascript - Retrieve value of a Jquery variable name containing a variable in itself -


in top of jquery i've got many variables (associated values) called : files_1, files_2, etc.

they created in script, in bottom of page :

<script> $(function () {     <?php foreach ($folders $f) { ?>     var files_<?=$f['request_id']?> = 0;     <?php } ?>     … }); </script> 

in html i've got link :

<a href="#" class="delete" data-request-id="2" title="delete">delete</a> 

data-request-id parameter gives me number, ones you've got in variables names on top. in example, it's data-request-id="2" : files_2.

next, i've got jquery function catch data values links :

$('.request-files').on('click', 'a.delete', function (e) {     e.preventdefault();     var $link = $(this);     var $id = $link.data('request-id');     console.log(files_$id); // <-- doesn't work }); 

what need retrieve value of variables files_x. in example, tried them using files_$id doesn't work.

any idea ?

if have variables defined in global scrope, attached window object. should able access variables using bracket notation on window object:

$('.request-files').on('click', 'a.delete', function (e) {     e.preventdefault();     var $link = $(this);     var $id = $link.data('request-id');     console.log(window['files_' + $id]); // <-- work }); 

upd: variables in closure of document.ready function ($(function() {...});), won't able access them other scopes. assume click handler within closure well. can suggest creating separate object properties named file_<id> - work alike window:

<script> $(function () {     var filesmap = {};     <?php foreach ($folders $f) { ?>     filesmap['files_' + <?=$f['request_id']?>] = 0;     <?php } ?>     …     $('.request-files').on('click', 'a.delete', function (e) {        e.preventdefault();        var $link = $(this);        var $id = $link.data('request-id');        console.log(filesmap['files_' + $id]);      }); }); </script> 

i not familiar php, string concatenation in request_id part might different, logic remains.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -