通过用户输入获取变量

Get variable via user input

本文关键字:获取 变量 输入 用户      更新时间:2023-09-26

我希望用户可以通过在文本区中写入变量的名称来看到变量的值,简化为:

var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"

是否可以输出(在本例中)"300美元"?

谢谢你的帮助!

不使用单独的变量,而是使用一个对象作为关联数组。

var variables = {
    'money': '300$'
}
var input = 'money';
alert(variables[input]);

你可以使用一个对象,然后在运行中定义一个变量作为该对象的属性:

var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);

一个简单的方法,你仍然可以尝试这个:

 var money = "300$";
 var input = "money"; //user wants to see money variable
 alert(eval(input)); //This would alert "money"

以下是使用文本区的答案

JSFiddle http://jsfiddle.net/7ZHcL/

<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');
        }
    })
});