属性值作为变量名[重复]

时间:2022-02-03 11:32:20

This question already has an answer here:

这个问题在这里已有答案:

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

我正在尝试将动态属性值用作var名称我拥有的内容:

$(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:

它给了我纯文本的价值。我想要的是它使用attr(“id”)值作为Var,如:

$(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.

基本上我想要一种动态的方式来调用某些id并将它们的属性值用作Var名称而不是纯文本。

1 个解决方案

#1


0  

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.

问题与这个问题几乎相同。

#1


0  

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.

问题与这个问题几乎相同。