2016-11-13 79 views
-6

函數應該返回「This is True」,但它看起來沒有工作。它告訴我''x''不是函數

randomQuestion沒有定義。

我在做什麼錯?

//Questions 
function randomQuestion() { 
    var quest = "this is true"; 
    var string_length = 1; 
    var randomstring = ""; 

    for (var i=0; i<string_length; i++) 
    { 
    var rnum = Math.floor(Math.random() * quest.length); 
    randomQuestion += quest.substring(rnum,rnum+1); 
    } 

    document.questions.questfield.value = randomQuestion; 
} 

<!--Questions form--> 
<form name="questions"> 
<input type="button" value="question" onClick="randomQuestion();">&nbsp; 
<input type="text" name="questfield" value=""> 
</form> 
+1

請以文本形式的代碼添加到這個問題。請在這裏看看:[mcve] –

+0

在函數中使用'randomQuestion'而不是'randomstring'。 – Cristy

+0

爲什麼隨機?該功能應該做什麼? –

回答

2

你的函數的名稱爲randomQuestion,但在你的功能,你寫:

randomQuestion += ... 

我注意到,你沒有在你的函數中使用變量randomstring。也許你想使用randomstring +=而不是使用randomQuestion += ...

這裏是我編輯的代碼:

<html> 
    <body> 
     <script> 
      function randomQuestion() { 
       var quest = "this is true"; 
       var string_length = 1; 
       var randomstring = ""; 
       var i = 0; 
       var rnum = 0; 
       for (i = 0; i < string_length; i++) { 
        rnum = Math.floor(Math.random() * quest.length); 
        randomstring += quest.substring(rnum, rnum + 1); 
       } 
       document.questions.questfield.value = randomstring; 
      } 
     </script> 
     <form name="questions"> 
      <input type="button" value="question" onclick="randomQuestion();"> 
      <input type="text" name="questfield" value=""> 
     </form> 
    </body> 
</html> 
+0

我想補充說,「randomQuestion」沒有定義的原因可能是原始海報沒有在腳本週圍放置腳本標籤。 – Espen

+0

他已將標籤放在腳本的周圍。在他編輯他的帖子之前,他的代碼截圖(現在被刪除) – zhuscat

+0

謝謝你的幫助!這真的幫助我推進我的項目。 –

1

我建議使用與任務的陣列,並使用隨機索引進行訪問。

function randomQuestion() { 
 
    var quest = ["this is true", "this is not true", "this is more true", "this is less true", "this is never true"]; 
 
    document.questions.questfield.value = quest[Math.floor(Math.random() * quest.length)]; 
 
}
<form name="questions"> 
 
    <input type="button" value="question" onClick="randomQuestion()">&nbsp; 
 
    <input type="text" name="questfield" value=""> 
 
</form>