【问题标题】:Whats the difference between if () {} and if () in javascriptjavascript中if(){}和if()有什么区别
【发布时间】:2011-08-12 16:08:58
【问题描述】:

我已经写了这段代码,这是一个 jquery 中的基本图片库

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

function rotateImages() {
     var curPhoto = $("#photoshow div.current");
     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")
     });
}

这行得通,除非我用 {} 包装 if 语句,但它不起作用。我只是想了解两者之间的区别以及为什么它不起作用。

【问题讨论】:

  • 因为您可能错误地放置了括号...您是否收到任何 javascript 错误?
  • 你把花括号放在哪里了?
  • 不客气。但重要的是你在未来(在 Stackoverflow 和其他地方)更清楚地表达你的问题,因此我认为你得到了反对票......
  • @mustafa:请删除您的评论。已更新您的代码
  • 抱歉 Naveen 感谢您为我编辑 :)

标签: javascript jquery if-statement curly-braces


【解决方案1】:

多行需要 {},否则 javascript 解释器不知道它还有更多的东西要运行。

试试这个,它必须工作:

$(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');
        });
    }
}

附注也请使用分号 (;) 来区分行。

【讨论】:

  • 感谢您的回复,抱歉没有使用分号,对js很陌生。我想到的问题是我把花括号放在你做的那样,因为图像不会淡入淡出。大括号需要放在行 nxtPhoto = $("#photoshow div:first");一旦我这样做了,它就开始工作了。谢谢你的回答:)
【解决方案2】:

如果一个 if 语句只有一个应该有条件地执行的语句,你可以去掉大括号。如果必须有条件地执行更多语句,则必须将它们作为大括号内的代码块包含在内。我的提示:总是写一对大括号,尤其是。如果你开始编程!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 2013-11-18
    • 2021-11-28
    • 2011-03-11
    • 2011-03-24
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    相关资源
    最近更新 更多