任何人都可以解释为什么这个JavaScript不会运行

时间:2013-04-23 15:09:02

标签: javascript jquery jquery-ui web-applications

我不是很好的机智JS和我只是不明白为什么这不会工作! 代码使用jquery将pulsate efect应用于我的div之一并永远运行,除非我用另一个函数停止它,但我无法弄清楚为什么我的第一段代码不会运行!

function animate(var x){
    // Do pulsate animation
    $(x).effect("pulsate", { times:4 }, 5000);
    // set timeout and recall after 10secs
    setTimeout(animate, 10000);
}
  $(document).ready(animate("#mydiv"));

让我这样做的唯一方法是让我这样做

function animate(){
    // Do pulsate animation
    $("#mydiv").effect("pulsate", { times:4 }, 5000);
    // set timeout and recall after 10secs
    setTimeout(animate, 10000);
}
  $(document).ready(animate);

请注意,在第一个代码段中,代码使用变量更有用,第二个部分的选择器名称为硬编码

3 个答案:

答案 0 :(得分:8)

不要在函数声明中使用var。只需使用:

function animate(x){

另外,你可能想要第一个例子:

function animate(x){
    return function () {
        function animateInner() {
            $(x).effect("pulsate", { times:4 }, 5000);
            setTimeout(animateInner, 10000);
        }
        animateInner();
    };
}
$(document).ready(animate("#mydiv"));

DEMO: http://jsfiddle.net/XHKbC/

否则,原始的animate("#mydiv")调用会立即执行(并且$(x)可能找不到任何内容,因为DOM还没有准备好)。 $(document).ready()期望对函数的引用。你调用了一个函数。但这都有点矫枉过正了。只需使用:

$(document).ready(function () {
    animate("#mydiv");
});

但您必须更改自己的功能,以便setTimeout同时传递x的值:

function animate(x){
    // Do pulsate animation
    $(x).effect("pulsate", { times:4 }, 5000);
    // set timeout and recall after 10secs
    setTimeout(function () {
        animate(x);
    }, 10000);
}

DEMO: http://jsfiddle.net/XHKbC/2/

虽然它的代码/复杂程度要高一些,但我的第一个例子并没有遇到问题(我必须通过使用闭包在x中传递setTimeout)。

<强>更新

如果您正在使用此代码,我会将其设置为:

function Animater(target) {
    var self = this;
    var animateTO;
    var animateElement = target;

    function animate() {
        animateElement.effect("pulsate", { times:4 }, 5000);
        animateTO = setTimeout(animate, 10000);
    }

    self.start = function () {
        animate();
    };

    self.stop = function () {
        animateElement.finish();
        clearTimeout(animateTO);
    };
}

并创建一个新的:

var mydivAnimater = new Animater($("#mydiv"));

然后,您可以在其上调用.start().stop(),然后根据需要在不同元素上创建任意数量的这些Animater个对象。

DEMO: http://jsfiddle.net/K7bQC/3/

答案 1 :(得分:3)

您的代码有两个问题:

省略var:

function animate(x){

修改您的事件处理程序:

$(document).ready(function(){
   animate("#mydiv");
});

您需要移交一个函数引用(animatefunction(){}),如果您通过animate(),则不要立即运行您正在执行的代码。

现在不要丢失对x的引用,你也必须在超时中修改动画调用:

setTimeout(function () {
        animate(x);
    }, 10000);

答案 2 :(得分:1)

在指定函数参数时,您无需键入 var

相关问题