2011-03-19 56 views
1

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

我的问题是:如何将表单中的字符串与数组中的字符串进行匹配。 我已经计算出迄今为止我需要一个for-string和一个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]; 
     } 
} 

} 
+0

嗨,你的问题是如何将表单元素的值传递给函数? – Bodman 2011-03-19 01:54:48

+0

弹出的第一件事就是你的for循环。在你的参数中你有变量'i',但是'str.match(charCommand [x])'使用'x'? – 2011-03-19 02:10:38

回答

0

你几乎有它的权利,
继承人我做了什么。

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

XML-tolkningsfel:EJvälformat 地址:http://www.ryuu.se/Gryning/game/index.xhtml Radnummer 27,Kolumn 22: 为(I = 0; I 2011-03-19 02:18:22

+0

我需要将它放在同一个文件中,还是可以在外部.js文件中使用它? – 2011-03-19 02:19:17

+0

您可以使用外部js文件。 我建议您使用JavaScript库,如JQuery寿。这使您可以使用文档就绪功能,并为您的代码提供简化。 – Bodman 2011-03-19 02:21:34

相关问题