2015-08-08 84 views
0

我的代码有一个名为'answer_textbox'的文本框。当用户在文本框中输入他们的答案并按下输入时,应该会发生一些jQuery代码。首先,我不知道如何有多个条件。他们应该是这样吗?多个IF条件

if($('#answer_textbox').val() == 4 && 'four') { 

之后代码执行我有一个否则,如果有弹出的是用户的法术“的”,而不是“四”的答案一个警告框。

if($('#answer_textbox').val() == 'for') { 
    alert('FOUR you moron'); 
} 

但是,这当用户法术“为”只会工作,而又不会让空间拼写之后。就像他们拼写'for'并且在它后面放置一个单独的空间一样,它将不起作用。我该如何解决?

+0

这个问题已经回答了*很多* *很多*次,什么样的研究做了你做?至于空间,请查看https://api.jquery.com/jQuery.trim/。 – Script47

+3

我实际上在嘲笑你的'提醒'。 – Akshay

+1

为什么你有这么多不相关的标签? – marstran

回答

0

您可以检查值这个词的索引:检查“为”字的价值存在:

if($('#answer_textbox').val().indexOf('for') >= 0) { 

您还可以修剪价值的空间,然后精确匹配:

if($('#answer_textbox').val().trim() == 'for') { 

....并与不区分大小写:

if($('#answer_textbox').val().trim().toLowerCase() == 'for') { 

然后关于你的多个if。它不会很好。你为什么这么做客户端?

if (condition) 
{ 

} 
else if (condition) 
{ 

} 
else if (condition) 
{ 

} 
else 
{ 

} 

不可维护。另一种方法是使用开关:

switch (field) 
{ 
    case: 'for': 
     // add your logic 
    break; 

    case 'other': 
     // add your logic 
    break; 

    default: 
     // logic for default 
} 
0

简短的回答是,你可以将所有的小写你的答案然后做$(selector).val().toString().toLowerCase().trim();获取用户输入的修剪小写值

然而,你可以使整个比你拥有的要简单得多。

我会做类似下面的事情。使用这种方法,添加或删除的问题是微不足道的,只需要添加的问题和答案给数组:

// create a multidimensional array of your questions and answers 
 
// answers should be in lowercase to make things easier later 
 
var questions=[ 
 
    ['What color is the sky?','blue'], 
 
    ['What color is the ocean?','blue'], 
 
    ['What comes after C?','d'], 
 
    ['What comes after 9?','10'] 
 
    ]; 
 
// loop through the array and add an input and text for each to the page 
 
$.each(questions,function(index,element){ 
 
    $('#container').append('<input type="text" class="answer"> '+ element[0]+'<br>') 
 
}); 
 
// when a user presses enter in one of the inputs, check the answer 
 
$('#container input').on('keydown', function(e){ 
 
    if(e.which == 13) { // enter was pressed 
 
     var question = $('.answer').index($(this)); // get the index of the current input 
 
     var answer = $(this).val().toString().toLowerCase().trim(); // get the typed answer 
 
     var correct = questions[question][1]; // get the correct answer for this question 
 
     if(answer==correct){ 
 
      $(this).removeClass('incorrect'); 
 
      $(this).addClass('correct'); // mark correct 
 
     } 
 
     else{ 
 
      $(this).removeClass('correct'); 
 
      $(this).addClass('incorrect'); // mark incorrect 
 
      $('#result').html(correct+' you moron'); // funny message 
 
      setTimeout(function(){ $('#result').html('') }, 2000); // remove message after a few seconds 
 
     } 
 
    } 
 
});
.correct{ 
 
    background-color:#99FF99; 
 
} 
 
.incorrect{ 
 
    background-color:#FF6666; 
 
} 
 
#result{ 
 
    color:#FF0000; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="result"> 
 
</div> 
 
<div id="container"> 
 
</div>