2011-03-19 53 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

相關問題