【问题标题】:JS: Fetch string from array that matches line in form-inputJS:从与表单输入中的行匹配的数组中获取字符串
【发布时间】:2011-03-19 01:49:28
【问题描述】:

我有一个带有文本输入和提交按钮的表单。在文本输入中,您可以编写简单的命令,例如 /look(创建一个简单的游戏,以尝试并提高我的技能)。 在 .js 文件中,我有一个包含一些命令/字符串的数组。

我的问题是:如何将表单中的字符串与数组中的字符串进行匹配。 到目前为止,我已经计算出我需要一个 for 字符串和一个 if/else 字符串,但我不知道该怎么做。

html 文件:

    <div id="commandField">
        <form method="POST" action="action" onSubmit="return commands(str);">
            <p class="center">Command: <input type="text" name="command" class="command" /><input type="submit" value="Execute" /></p>
        </form>
    </div>

javascript 文件:

function commands(str)
{
    var charCommand=new Array(); // regular array (add an optional integer
    charCommand[0]="/look";       // argument to control array's size)
    charCommand[1]="/use";
    charCommand[2]="/continue";
    charCommand[3]="/pickup";

    for(i=0 ; i < charCommand.length ; i++)
{
    if(str.match(charCommand[x]))
        {
            document.getElementById("commandField").innerHTML=charCommand[x];
        }
}

}

【问题讨论】:

  • 嗨,你的问题是如何将表单元素的值传递给函数?
  • 首先弹出的是你的for循环。在您的参数中,您有变量 istr.match(charCommand[x]) 正在使用 x

标签: javascript arrays string forms match


【解决方案1】:

你几乎是对的,
这就是我所做的。

<script type="text/javascript">
        function commands(form)
    {
        var str = form.command.value;
       var charCommand=new Array(); // regular array (add an optional integer
        charCommand[0]="/look";       // argument to control array's size)
        charCommand[1]="/use";
        charCommand[2]="/continue";
        charCommand[3]="/pickup";

        for(i=0 ; i < charCommand.length ; i++)
    {
        if(str.match(charCommand[i]))
            {
                document.getElementById("commandField").innerHTML=charCommand[i];
            }
    }
    }



    </script>
    </head>
    <body>
        <div id="commandField">
            <form method="GET" action="">
                <p class="center">Command: <input type="text" name="command" class="command" />
                <input type="button" value="Execute" onClick="commands(this.form)"/></p>
            </form>
        </div>
    </body>
    </html>

【讨论】:

  • XML-tolkningsfel: ej välformat 地址: ryuu.se/Gryning/game/index.xhtml Radnummer 27, Kolumn 22: for(i=0 ; i
  • 我需要将它放在同一个文件中还是可以在外部 .js 文件中使用它?
  • 可以使用外部js文件。我建议您使用像 JQuery 这样的 Javascript 库。这允许您使用文档准备功能,并简化您的代码。
  • 我对 jQuery 有点熟悉,但我不知道在这种情况下它有什么帮助。而且你的脚本对我不起作用,我很害怕。
  • 你的文件名是错误的,它需要是 .html 而不是 .xhtml,这就是你的 javasript 没有执行的原因
猜你喜欢
  • 2014-02-06
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 2019-04-08
相关资源
最近更新 更多