如果那么声明不在jquery中工作

时间:2012-04-18 01:35:56

标签: javascript jquery css

我正在尝试创建一个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);
        });
    }

});​

1 个答案:

答案 0 :(得分:7)

JavaScript区分大小写。 if/else,而不是If/Else。并且使用==进行比较。如果您打算6,请执行$num,错误地将if ($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);});
    }
});

习惯使用网络浏览器的错误控制台。 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);