我有兩個變量totalGuess和condensedAnswer。我正在創建一個jQuery點擊事件,如果totalGuess不等於condensedAnswer,那麼點擊事件不會發生,並且一個名爲message的div將顯示消息「對不起,但您的答案不正確,請重試。」javascript變量總是不相等
問題是,total語句在if語句永遠不會等於condensedAnswer。我試着看到typeof,它們都是字符串。我試過console.log(totalGuess +「\ n」+ condensedAnswer);他們都返回相同的價值。我試過對condensedAnswer進行硬編碼,totalGuess可以等於硬編碼的答案。但是,當我嘗試將硬編碼答案與condensedAnswer進行比較時,即使condensedAnswer的console.log值相同,也不相等。我不是什麼問題。
下面的代碼片段:
$('.submitGuess').click(function(e){
var totalGuess = "";
var condensedAnswer = answer.replace(new RegExp(" ","g"), "");
$('.crypto-input').each(function(){
totalGuess += $(this).val();
});
// if incorrect guess
if(totalGuess !== condensedAnswer) {
$('.message').text("Sorry, but your answer is incorrect. Please try again.");
e.preventDefault();
}
// if user wins, congratulate them and submit the form
else {
return true;
}
});
如果有幫助,這裏的頁面,只是一個隨機測試密碼WordPress插件: http://playfuldevotions.com/archives/140
這是一個可怕的做法,它幾乎肯定會失敗*很多*。您將所有輸入值相加並與一個字符串進行比較,在該字符串中,您爲一個輸入刪除了所有空格,一個字符或錯誤位置的空格,並且失敗。 – adeneo
適用於我:http://jsfiddle.net/8wndm/輸入'foobarbar'並且猜測是正確的。問題可能在其他地方,或者與您未顯示的代碼有關。 –
@ adeneo它基本上是一個縱橫字謎...它是從文本框中建立一個字符串。 – epascarello