2015-04-19 34 views
1

正確或錯誤的答案輸出並迅速消失。我如何獲得答案留在屏幕上。我想保持html和js文件獨立。我後來想要做的是添加其他短語的程序。 謝謝。結果輸出消失太快

帕烏

INDEX.HTML

<head> </head> 
<body> 
    <form name="myForm"> 
     <div id ="phrase"></div>  
     <input type = "text" id = "textinput"> 
     <button id="myBtn">Click here</button> 
     <div id ="feedback"></div> 
    </form> 
    <script src = "phraseScrambler.js"></script>  
</body> 
</html> 

PHRASESCRAMBLER.JS

var words = ['how', 'are', 'you', 'today?']; 
var correctInput = "how are you today"; 
var userInput = 'how are you today?'; 
var newWords = words.slice(0); 
shuffle(newWords); 
question(); 

function question() { 
    var el = document.getElementById('phrase'); 
    el.textContent = newWords.join(' '); 
    document.getElementById("myBtn").onclick = checkAnswer;} 

function checkAnswer() { 
    var elMsg = document.getElementById('feedback'); 
    if (document.myForm.textinput.value == correctInput) { 
     elMsg.textContent= "correct";} 
    else { 
     elMsg.textContent= "wrong answer";}} 

function shuffle(newWords) { 
    var counter = newWords.length, temp, index; 
    while (counter > 0) { 
    index = Math.floor(Math.random() * counter); 
    counter--; 
    temp = newWords[counter]; 
    newWords[counter] = newWords[index]; 
    newWords[index] = temp;} 
    return newWords;} 
+0

您的按鈕在點擊時提交表單。不要使用默認行爲或使用'

回答

1

首先,不綁定,如果你想處理表單提交的點擊事件,形式有專門的事件稱爲onsubmit。當表單被提交時,默認的瀏覽器行爲是導航到表單動作(在你的情況下重新加載頁面)。您需要通過從onsubmit處理程序返回false來防止此問題。

更正HTML將(我給一個ID的形式):

<form name="myForm" id="myForm"> ... </form> 

然後事件處理的樣子(注意return false;checkAnswer功能):

var words = ['how', 'are', 'you', 'today?']; 
 
var correctInput = "how are you today"; 
 
var userInput = 'how are you today?'; 
 
var newWords = words.slice(0); 
 
shuffle(newWords); 
 
question(); 
 

 
function question() { 
 
    var el = document.getElementById('phrase'); 
 
    el.textContent = newWords.join(' '); 
 
    document.getElementById("myForm").onsubmit = checkAnswer; 
 
} 
 

 
function checkAnswer() { 
 
    var elMsg = document.getElementById('feedback'); 
 
    if (document.myForm.textinput.value == correctInput) { 
 
     elMsg.textContent = "correct"; 
 
    } else { 
 
     elMsg.textContent = "wrong answer"; 
 
    } 
 
    return false; 
 
} 
 

 
function shuffle(newWords) { 
 
    var counter = newWords.length, 
 
     temp, index; 
 
    while (counter > 0) { 
 
     index = Math.floor(Math.random() * counter); 
 
     counter--; 
 
     temp = newWords[counter]; 
 
     newWords[counter] = newWords[index]; 
 
     newWords[index] = temp; 
 
    } 
 
    return newWords; 
 
}
<form name="myForm" id="myForm"> 
 
    <div id ="phrase"></div>  
 
    <input type = "text" id = "textinput" /> 
 
    <button>Click here</button> 
 
    <div id ="feedback"></div> 
 
</form>