开发者

Whats the difference between if () {} and if () in javascript

I've written this code, which is a basic image gallery in jquery

$(document).ready(function() {
 setInterval("rotateImages()",2000)
 })

function rotateImages() {
     var curPhoto = $("#photoshow div.current")开发者_Go百科;
     var nextPhoto = curPhoto.next();
     if (nextPhoto.length == 0) {
         nextPhoto = $("#photoshow div:first");
     }
     curPhoto.removeClass("current").addClass("previous");
     nextPhoto.css({
         opacity: 0.0
     }).addClass("current").animate({
         opacity: 1.0
     }, 1000‌​, function () {
         curPhoto.removeClass("previous")
     });
}

This works, except when I wrap the if statement with {} it doesn't. I just wanted to understand the difference between the two and why it wouldn't work.


multiple lines need {}, otherwise the javascript interpreter doens't know it has more things to run.

try this, it has to work:

$(document).ready(function() {
    setInterval("rotateImages()", 2000);
})

function rotateImages() {
    var curPhoto = $("#photoshow div.current")
    var nxtPhoto = curPhoto.next();

    if (nxtPhoto.length == 0) {
        nxtPhoto = $("#photoshow div:first");
        curPhoto.removeClass('current').addClass('previous');
        nxtPhoto.css({
            opacity: 0.0
        }).addClass('current').animate({
            opacity: 1.0
        }, 1000, function() {
            curPhoto.removeClass('previous');
        });
    }
}

P.S. please also use semi-colons (;) to differentiate lines.


If an if-statement has only one statement that should be executed conditionally, you can leave away the braces. If more statements must be executed conditionally you have to embrace them as a block of code within braces. My tip: write always a pair of braces, esp. if you are beginning programming!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜