繁体   English   中英

JS:从与表单输入中的行匹配的数组中获取字符串

[英]JS: Fetch string from array that matches line in form-input

我有一个带有文本输入和提交按钮的表单。 在文本输入中,您编写了/ 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];
        }
}

}

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

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM