嵌套JS if语句无法正常工作

时间:2017-01-18 21:23:44

标签: javascript jquery click counter nested-if

我使用计数器在每次点击时显示适当的信息,但我无法通过一次点击使按钮工作。我相信我正确地添加到我的计数器,但由于某种原因,它没有正确注册。任何修改都将不胜感激。



$(document).on("click", ".proceedBtn", function() {
            $i = 0;
            $i = $i + 1;
            if ($i == 1){
                if ($i == 2){
                    $('#billingQuestions').hide();
                    $('#billingQuestions2').hide();
                    $('#noQuestions').hide();
                    $('#noQuestions2').hide();
                    $('#paymentInfo').show();
                    $('#paymentInfo2').show();
                    $('.arrow').css('left', '84%');
                    console.log("payment");
                    return;
                } 
                $('#noQuestions').show();
                $('#noQuestions2').show();
                $('#billingQuestions').hide();
                $('#billingQuestions2').hide();
                $('#paymentInfo').hide();
                $('#paymentInfo2').hide();
                $('.arrow').css('left', '50%');
                $i++;
                console.log("shipping");
                return;
            }       
        });




2 个答案:

答案 0 :(得分:2)

请记住,每次点击后都会执行函数内的所有内容。

$(document).on("click", ".proceedBtn", function() {
    $i = 0;              // On every click $i is reset to 0
    $i = $i + 1;         // Now $i == 1
    if ($i == 1) {       // So this condition is always true
        if ($i == 2) {   // And this condition is always false
            ...          // That's why this part is never executed
        }
    }
}

你可能需要的是:

$i = 0;
$(document).on("click", ".proceedBtn", function() {
    $i = $i + 1;
    if ($i == 1){
        $('#noQuestions').show();
        $('#noQuestions2').show();
        $('#billingQuestions').hide();
        $('#billingQuestions2').hide();
        $('#paymentInfo').hide();
        $('#paymentInfo2').hide();
        $('.arrow').css('left', '50%');
        console.log("shipping");
    }       
    else if ($i == 2){
        $('#billingQuestions').hide();
        $('#billingQuestions2').hide();
        $('#noQuestions').hide();
        $('#noQuestions2').hide();
        $('#paymentInfo').show();
        $('#paymentInfo2').show();
        $('.arrow').css('left', '84%');
        console.log("payment");
    } 
});

答案 1 :(得分:0)

单击时,$ i变量始终为0,因此当$ i + 1的总和始终为1时。

除此之外,你的页面中有很多ID,你不能用你想要隐藏和显示的元素的类吗?检查页面结构,您可以优化您的HTML及其类/ ID