1

I'm trying to get a dynamic attribute value to be used as a var name What I have:

$(this).html(""+$(this).attr("id")+"");  

It gives me the value as plain text. What I want is that it uses the attr("id") value as a Var like:

$(this).html(""+myVar+"")

Final example:

<div class="text" id="text1"></div>
<div class="text" id="text2"></div>


var text1 = "hello world"
var text2 = "bye world"
$(document).ready(function () {
   $(".text").click(function(){
      $(this).html(""+$(this).attr("id")+"");  
   });
});

Basically I want a dynamic way of calling to certain id's and getting their attribute value to be used as the Var name instead of plain text.

Ian Hogers
  • 45
  • 1
  • 9

1 Answers1

1

It all depends on variable namespace and scope, but generally next code should do the job.

$(".text").click(function(){
    var varFromAttr = window[$(this).attr("id")];
    $(this).html(varFromAttr);
});

Question is almost the same as this question.

Community
  • 1
  • 1
Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51