我希望用户可以通过在textarea中写下它的名字来查看变量的值,简化:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
甚至可以输出(在此示例中)" 300 $"?
感谢您的帮助!
答案 0 :(得分:2)
使用对象作为关联数组,而不是单独的变量。
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
答案 1 :(得分:0)
您可以使用一个对象,然后在该对象上定义一个变量作为该对象的属性:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
答案 2 :(得分:0)
一种简单的方法,你仍然可以尝试这个:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
答案 3 :(得分:0)
以下是按照要求使用textarea的答案。
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
<强> JQuery的强>
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});