【问题标题】:Is it possible to use the value of a variable to define the name of another variable in a JavaScript string?是否可以使用变量的值来定义 JavaScript 字符串中另一个变量的名称?
【发布时间】:2013-01-23 02:48:53
【问题描述】:

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

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

我什至不擅长 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 的内容是相应表单输入的值元素。这可能吗?它必须是,对吧?我只是没有受过足够的教育来做看似相当简单的事情。

【问题讨论】:

  • 天哪,我喜欢这个网站。与成千上万比我更聪明的人即时联系,他们积极喜欢帮助像我这样的傻瓜。 Stackoverflow 规则
  • 不是很好吗?直到你找到那些把这种方式看得太认真的人

标签: javascript variables variable-assignment session-cookies


【解决方案1】:

我不确定您是否以正确的方式进行操作,仅此而已 - 无需创建变量并将其命名为特定的表单元素。不是传递'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的参数来引用它。它似乎比使用文本来指定表单中元素的名称要干净得多......特别是因为在你的示例中,文本总是引用它被调用的元素。

【讨论】:

    【解决方案2】:

    你想看看方括号符号。

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

    您可能应该使用设置 cookie 功能。查看MDN docs

    【讨论】:

      【解决方案3】:

      您可以使用全局对象:

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

      但这肯定不是 Ian 指出的正确方法。

      【讨论】:

      • 不一定是正确的方式本身,但从技术上讲,它是我所问问题的答案:) 所以今晚我学到了两个新东西,而不是一个:D
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2021-08-22
      相关资源
      最近更新 更多