2013-04-11 68 views
0

我正在做一個測驗,答案是隨機的。我想要「正確!」 div顯示文本框的值是否與另一個div相同。當文本框的值與另一個div的內容相同時顯示div

這裏是我到目前爲止有:

$(document).ready(function(){ 
    $("#buttontest").click(function(){ 
     if ($('#full_day').val() == '#answer') { 
      $("#correct").show("fast"); //Slide Down Effect 
     } 
     else { 
      $("#correct").hide("fast"); //Slide Up Effect 
      $("#incorrect").show("500").delay("1000").hide("500"); 
     } 
    }); 
}); 
<p>What is the animal?</p> 
<div id="correct"> 
    That's Correct! 
</div> 
<div id="incorrect"> 
    Sorry, Try again! 
</div> 
<div id="answer">Monkey</div> 
<input type='text' id="full_day"/> 
<input type='button' id="buttontest" value="clickme"/> 
+0

你的問題是什麼? – 2013-04-11 11:57:21

+0

基本上保持div標籤屬性顯示無和($('#full_day')。val()== $('#answer')。html()) – 2013-04-11 12:01:40

回答

1
if ($('#full_day').val() == $('#answer').text()) 

這是區分大小寫的。爲了使它不區分大小寫:

if ($('#full_day').val().toLowerCase() == $('#answer').text().toLowerCase()) 

編輯:按照要求,這裏是一個解決方案,它允許多個答案:

$('#check').bind('click', function() { 
    var possibleAnswers = $('#answers').text().toLowerCase().split(' '); 
    var givenAnswer = $('#user-answer').val().toLowerCase(); 
    var isAnswerCorrect = false; 
    for (var indexPossibleAnswers = 0; indexPossibleAnswers < possibleAnswers.length; indexPossibleAnswers++) 
    { 
     if (possibleAnswers[indexPossibleAnswers] == givenAnswer) 
     { 
       isAnswerCorrect = true 
       break; 
     } 
    } 
    if (isAnswerCorrect) 
    { 
     alert('Correct'); 
    } 
    else 
    { 
     alert('Incorrect, try again.'); 
    } 
}); 

Live demonstration.

+0

由於'answer'是一個'div',因此不存在'val'屬性...您應該使用'.text()'代替... – 2013-04-11 12:02:13

+0

正好,剛注意到這一點並編輯了我的文章。 – dislick 2013-04-11 12:03:10

+0

謝謝! <3 – user1890129 2013-04-11 12:16:03

1
$(document).ready(function(){ 
    $("#buttontest").click(function(){ 

     if ($('#full_day').val() == $('#answer').html()) { 
      $("#correct").show("fast"); //Slide Down Effect 
     } 
     else { 
      $("#correct").hide("fast"); //Slide Up Effect 
      $("#incorrect").show("500").delay("1000").hide("500"); 
     } 
    }); 
}); 

<p>What is the animal?</p> 
<div id="correct" style="display:none;"> 
    That's Correct! 
</div> 
<div id="incorrect" style="display:none;"> 
    Sorry, Try again! 
</div> 
<div id="answer" style="display:none;">Monkey</div> 
<input type='text' id="full_day"/> 
<input type='button' id="buttontest" value="clickme"/> 
+0

如果文本框的值是與一個wourld的div一樣嗎?假設div包含「動物豬」,那麼只有「豬」會給出「正確!」 div和「動物」將永遠被忽略? – user1890129 2013-04-11 12:25:22

3

使用

$('#answer').text() 

,而不是隻

'#answer' 

在if語句中。

+0

我們可以得到在這樣的div標籤之間的文字? – 2013-04-11 12:08:24

+0

多數民衆贊成在偉大的。如果我不能得到一個div的價值,那麼我的腦海裏只有一個假設,那就連文本都沒有。 – 2013-04-11 12:15:40

+0

是的。對於'

Monkey
'這個$('#answer')。text()'應該返回「Monkey」。 **在這裏我添加了一個jsfiddle:http://jsfiddle.net/btddn/** – 2013-04-11 12:19:13

相關問題