Evaluate the value of a variable to convert it into a variable

1

This is a line inside a for in with jQuery append:

<span id="TITLE'+i+'" 
      class="card-title activator grey-text text-darken-4">'
    +$(".card-title").attr("id")
+'<i class="material-icons right">more_vert</i></span>'+

When i=1 , I want the part of

to be resolved
TITLE'+i+'

with the value of that variable (for example, to evaluate the value of TITLE1 , TITLE2 , etc.). And the same in the part where the text of the span is, that is to say in:

$(".card-title").attr("id")

to be taken as a variable and take the value that corresponds to the variable TITLE1 in JavaScript.

  

I saw that in PHP you can do something similar to $$Nombre_de_Variable , but I do not know how to do it here.

If someone can help me or know of an alternative, I would appreciate it.

    
asked by Edwin Anaya 07.02.2017 в 23:21
source

3 answers

1

Deal with this:

var variable = eval($(".card-title").attr("id"));

$(".card-title").attr("id") returns TITLE1 as string, eval evaluates the expression passed to it as a string, so if there is a variable called TITLE1 it should return its value as a result of evaluating the expression

    
answered by 08.02.2017 / 06:02
source
1

Thank you all for your contribution, your collaboration was useful and I found the Answer. Exactly the eval () function was what I needed.

var tam = 2;
var jqRow = jQuery('.row');
var pretitle = "TITLE";
var title = "";
var TITLE1 = "My First Project";
var TITLE2 = "My Second Project";
for (i=1;i<=tam; i++){
  title = pretitle + i;
  jqRow.append('<span id="' + eval(title) +'" class="card-title activator grey-text text-darken-4">' + eval(title) + '<i class="material-icons right"> more_vert</i></span><br>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row"></div>
    
answered by 08.02.2017 в 14:03
0

It would be something like that

var tam = 5;
var jqRow = jQuery('.row');
var pretitle = "TITLE";
var title = "";
for (i=1;i<=tam; i++){
  title = pretitle + i;
  jqRow.append('<span id="' + title +'" class="card-title activator grey-text text-darken-4">' + title + '<i class="material-icons right">more_vert</i></span><br>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row"></div>
    
answered by 08.02.2017 в 06:13