javascript中if(){}和if()有什么区别
我已经编写了这段代码,它是 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 语句时,它不起作用。我只是想了解两者之间的区别以及为什么它不起作用。
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");
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
多行需要 {},否则 javascript 解释器不知道它还有更多东西要运行。
试试这个,它必须工作:
PS 请也使用分号 (;) 来区分行。
multiple lines need {}, otherwise the javascript interpreter doens't know it has more things to run.
try this, it has to work:
P.S. please also use semi-colons (;) to differentiate lines.
如果 if 语句只有一个应有条件执行的语句,则可以省略大括号。如果必须有条件地执行更多语句,则必须将它们作为大括号内的代码块包含起来。我的建议:总是写一对大括号,尤其是。如果您正在开始编程!
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!