2017-03-09 89 views
0

我的问题如下:我想要实现一个(真的)小应用程序,我要在其中生成一个字母(在A和E之间),并将其与后来制作的用户输入进行比较。如果用户输入与生成的字母不一样,则会弹出一条消息,告诉用户他做出了错误的选择。如果用户做出了正确的选择,则计数器获得+1,并且如果用户达到5分中的至少3分,则他赢得奖励。用户在脚本结束前有3次尝试。将生成的字母与用户输入进行比较

障碍是我的主要焦点在于php。我在JavaScript中的知识并不多。

所以我的脚本在用户键入他的答案时不会做任何事情。

+1

你不是触发功能的输入值发生变化的时候?尝试在用户写入或字段中的值更改时运行比较。 – yomisimie

+2

在'compare'里面移动'which = document.getElementById('which')。value' – Rajesh

+0

也有一些问题'(var i = 0; i <1; i ++)'为什么?另外'else {if(...){}}'?你可以使用'else if'。同样在我的理解中,正确的分数应该只是递增,并且控制功能应该不同 – Rajesh

回答

0

已解决! 下面的代码是解决方案。

String.prototype.last = function(){ 
 

 

 
return this[this.length - 1] 
 
} 
 
;(function() { 
 
    var score = 0; 
 
    var text = ""; 
 
    var possible = "ABCDE"; 
 
    var noOfTries = 5; 
 

 
    function generateCharacter() { 
 
    var index = Math.floor(Math.random() * 100) % possible.length; 
 
    text = possible[index]; 
 
    possible = possible.slice(0, index) + possible.slice(index+1); 
 
    alert(text); 
 
    return text; 
 
    } 
 

 
    function validate(string) { 
 
    return (string || "").trim().last() === text.last(); 
 
    } 
 

 
    function handleChange(){ 
 
    \t var valid = validate(this.value); 
 
    if(valid){ 
 
    \t score++; 
 
     alert("Richtig!"); 
 
    }else{ 
 
    \t alert("Das war leider falsch. Die richtige Antwort wäre " + text + " gewesen!"); 
 
    } 
 
    console.log(this.value.length === noOfTries) 
 
    this.value.length === noOfTries ? notify() : generateCharacter(); 
 
    } 
 
    
 
    function notify(){ 
 
    \t if(score == 0) { 
 
    \t alert("Schade! Sie haben " + score + " Punkte erreicht! Nochmal?"); 
 
    }else if(score >= 1 && score <3){ 
 
    \t alert("Schade! Sie haben lediglich " + score + " von 5 Punkten erreicht! Nochmal?"); 
 
    }else if(score >= 3 && score <= 5) { 
 
     alert("Herzlichen Glückwunsch! Sie haben " + score + " von 5 Punkten erreicht!"); 
 
    } 
 
    } 
 
    
 
    function registerEvent(){ 
 
    \t document.getElementById('which').addEventListener('keyup', handleChange); 
 
    } 
 
    registerEvent(); 
 
    generateCharacter(); 
 
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
    <label for="which">Antwort? </label> 
 
    <input type="text" name="which" id="which" placeholder="#" style="width: 9px;">

而这里的小提琴:Compare generated string with user input

相关问题