2014-03-03 50 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"; 
    }; 
    }); 

试试这个