是否可以使用变量的值来定义JavaScript字符串中另一个变量的名称?

时间:2013-01-23 02:48:54

标签: javascript variables variable-assignment session-cookies

我正在尝试使用变量的值作为字符串中另一个变量的名称。

我已经搜索过,并且看到了类似的问题,答案似乎是“学习如何使用数组,虚拟”。但我认为这个问题有点独特。

我对Javascript的解释不够好,所以只显示代码可能更容易,我包围了我在双星(**)中困惑的部分:

<script language="JavaScript">
function bake(cookietype,ingredient) {
    **ingredient**=document.recipes.**ingredient**.value;
    document.cookie=**cookietype** + "=" + **ingredient**;
}
</script>

<form name="recipes">
    Name: <input type="text" name="flour" size="20" onBlur="bake('oreo','flour')">
    Email: <input type="text" name="eggs" size="20" onBlur="bake('milano','eggs')">
</form>

所以如果这有任何意义,我想设置一个以传递给函数'bake'的第一个变量命名的cookie,并且我希望cookie的内容是相应表单输入的值元件。这可能吗?它必须是,对吧?我只是没有受过足够的教育去做看似简单的事情。

3 个答案:

答案 0 :(得分:3)

我不确定你是以正确的方式去做,是全部 - 不需要创建变量并将其命名为特定的表单元素。不要将'flour'作为第二个参数传递,而是传递this ...所以它将是onBlur="bake('oreo',this)"。然后,在您的函数中,您可以使用ingredient.value来获取表单输入的值。以下是我用作函数的内容:

function bake(cookietype,ingredient) {
    var textbox_value=ingredient.value;
    document.cookie=cookietype + "=" + textbox_value;
}

HTML:

<form name="recipes">
    Name: <input type="text" name="flour" size="20" onBlur="bake('oreo',this)">
    Email: <input type="text" name="eggs" size="20" onBlur="bake('milano',this)">
</form>

this指的是从中调用的HTML元素。因此,当您将其传递给函数时,可以通过名为ingredient的参数来引用它。它似乎比使用文本指定表单中元素的名称要清晰得多......特别是因为在您的示例中,文本始终引用它所调用的元素。

答案 1 :(得分:2)

您想要查看方括号表示法。

function bake(cookietype,ingredient) {
    var ingredient=document.recipes[ingredient].value;
    document.cookie= cookietype + "=" + ingredient;
}

你可能应该使用set cookie函数。查看MDN docs

答案 2 :(得分:1)

您可以使用全局对象:

var myVars = {};
function bake(cookietype,ingredient) {
    myVars[ingredient] = document.recipes[ingredient].value;
    document.cookie = cookietype + "=" + myVars[ingredient];
}

但是,正如伊恩指出的那样,这肯定不是正确的方式。

相关问题