1

我正在尝试创建一个 if then 语句来为幻灯片创建一个循环,幻灯片在没有 if then 语句但不会循环的情况下工作。有了声明,它就是行不通的。这是代码

var $num = null;
$num = parseInt(0, 10);
$("document").ready(function onReady() {
    If($num = 6) {
        $num = parseInt(0, 10);
        $num = parseInt($num, 10) + 1;
        var final = "#img" + $num;
        $(final).fadeTo(3000, 1, function() {
            $(final).fadeTo(3000, 0, onReady);
        });
    }
    Else {
        $num = parseInt($num, 10) + 1;
        var final = "#img" + $num;
        $(final).fadeTo(3000, 1, function() {
            $(final).fadeTo(3000, 0, onReady);
        });
    }

});​
4

1 回答 1

7

JavaScript 区分大小写。 if/else,不是If/Else。比较是用==. 当您打算检查时,您错误地分配6给。$numif ($num = 6)($num == 6)

// No need for this:
// $num = parseInt(0,10);
// Just initialize to zero
var $num = 0;
// However, since you initialized it, it will _never_ be 6 on page load as you test for...
// So maybe you don't actually want this...    

// Fix the $(document).ready()  
$(document).ready(function() {

   // Never going to be 6 since you initialized to zero...
   if ($num == 6 ){
        $num = parseInt(0,10);
        $num = parseInt($num,10) + 1;
            var final = "#img" + $num;
            $(final).fadeTo(3000,1, function() {$(final).fadeTo(3000,0, onReady);});
    }
    else{
        $num = parseInt($num,10) + 1;
        var final = "#img" + $num;
        $(final).fadeTo(3000,1, function() {$(final).fadeTo(3000,0, onReady);});
    }
});

习惯使用 Web 浏览器的错误控制台。Firefox 11 内置了一个,或者 Firebug 是一个出色的扩展。Chrome/Safari 有开发者工具,IE 按 F12 进入控制台。错误将在控制台上报告。

更新:

在第二次阅读时,也许您实际上是在尝试将其定义onReady为函数并将其传递给$(document).ready(). 在这种情况下,这是合适的方法。

// If this is the correct intent, then it _does_ make sense to initialize $num 
// since it will be modified when onReady is called
var $num = 0;

// Define the onReady function
function onReady() {
   // Never going to be 6 since you initialized to zero...
   if ($num == 6 ){
        $num = parseInt(0,10);
        $num = parseInt($num,10) + 1;
            var final = "#img" + $num;
            $(final).fadeTo(3000,1, function() {$(final).fadeTo(3000,0, onReady);});
    }
    else{
        $num = parseInt($num,10) + 1;
        var final = "#img" + $num;
        $(final).fadeTo(3000,1, function() {$(final).fadeTo(3000,0, onReady);});
    }
}
// Pass the defined function to ready()
$(document).ready(onReady);
于 2012-04-18T01:38:43.883 回答