2014-03-03 49 views
0

我正在寫一個jQuery測驗。jquery不能得到其他工作

首先,我根據在頁面上設置變量:

if ($("body").hasClass("questionone")){ 
    var $currentQuestion = 1; 
    console.log($currentQuestion); 
    } 
    else if ($("body").hasClass("questiontwo")){ 
    var $currentQuestion = 2; 
    console.log($currentQuestion); 
    } 
    else if ($("body").hasClass("questionthree")){ 
    var $currentQuestion = 3; 
    console.log($currentQuestion); 
    }; 

然後,當他們回答一個問題,我有一個彈出,上面寫着不正確或正確的,一個按鈕,說下一個問題。下一個問題按鈕重新定向取決於currentQuestion變量的內容。問題是,它的工作原理爲,如果部分,並重新引導從問題1第2題上點擊,但問題2不重定向到問題3

這裏是重定向代碼:

$(".nextquestion").on("click", function(){ 
    if($currentQuestion = 1) { 
     window.location.href = "question2.html"; 
    } 
    else if($currentQuestion = 2) { 
     console.log("thisworks"); 
     window.location.href = "question3.html"; 
    } 
    else if($currentQuestion = 3) { 
     window.location.href = "question4.html"; 
    }; 
    }); 

感謝您的幫助。

回答

4

更改======,讓你不分配不只是比較:

if($currentQuestion === 1) { 
... 
else if($currentQuestion === 2) { 
... 
else if($currentQuestion === 3) { 

請避免重複var聲明(var $currentQuestion = 2;),它使代碼難以破譯。

+0

完美工作的感謝。我會在幾分鐘後讓我接受答案。 – jckly

+1

或'==='確保你只是比較而不是轉換*然後*比較。 – James

+0

@詹姆斯你是對的,它通常更好。我更新了。 –

0
if ($("#body").hasClass("questionone")){ 
    var $currentQuestion = 1; 
    console.log($currentQuestion); 
    } 
    else if ($("#body").hasClass("questiontwo")){ 
    var $currentQuestion = 2; 
    console.log($currentQuestion); 
    } 
    else if ($("#body").hasClass("questionthree")){ 
    var $currentQuestion = 3; 
    console.log($currentQuestion); 
    }; 

$(".nextquestion").on("click", function(){ 
    if($currentQuestion == 1) { 
     window.location.href = "question2.html"; 
    } 
    else if($currentQuestion == 2) { 
     console.log("thisworks"); 
     window.location.href = "question3.html"; 
    } 
    else if($currentQuestion == 3) { 
     window.location.href = "question4.html"; 
    }; 
    }); 

試試這個