将HTML元素传递给Javascript函数

时间:2011-05-07 20:49:07

标签: javascript jquery html parameters

我知道这已经得到了解答,但似乎没有一个问题与我的观点相关。我的代码如下。我需要将变量$dynamicPanel传递给第二个函数,或者将this传递给第二个函数。无论哪种方式都可以接受。

虽然我们正在使用它,但有没有办法可以等待几秒钟来执行FirstAnimation函数而无需再次使用animate()方法。

$(document).ready(function FirstAnimation() {
    var $dynamicPanel = $(".dynamicPanel");
    $('.dynamicPanel').animate({
        opacity: 0,
        left: '100'
    }, 5000, function () {
        alert('first animation complete');
        SecondAnimation(this);
    });
});

function SecondAnimation(this) {
    $(this).animate({
        opacity: 1
    }, 100, function () {
        alert('second animation complete');
        FirstAnimation();
    });
};

4 个答案:

答案 0 :(得分:2)

this是保留字,不能用作参数名称。你应该这样做:

$(document).ready(function(){
   FirstAnimation();
});

function FirstAnimation() {
   //this function doesn't change, use your code
};

function SecondAnimation(elem) {         
    $(elem).animate({
        opacity: 1
    }, 100, function () {
        alert('second animation complete');
        setTimeout(function(){  //Delay FirstAnimation 7 seconds
           FirstAnimation();
        }, 7000);
    });    
};

希望这会有所帮助。干杯

答案 1 :(得分:0)

如何将SecondAnimation(this);更改为SecondAnimation($dynamicPanel);?看起来它会做你想做的事。

答案 2 :(得分:0)

可以使用 jQuery.delay()

完成此等待
$(document).ready(function FirstAnimation() {
    var $dynamicPanel = $(".dynamicPanel");
    $dynamicPanel.animate({
        opacity: 0,
        left: '100'
    }, 5000, function () {
        alert('first animation complete');
        SecondAnimation($dynamicPanel); // <--pass the proper variable ;)
    });
});

function SecondAnimation(this) {
    $(this).delay(5000).animate({ //<<-- wait five seconds
        opacity: 1
    }, 100, function () {
        alert('second animation complete');
        FirstAnimation();
    });
};

然而,您可以调用整个函数递归并将动画设置作为数组中的参数传递。因此,您重用该功能,仅更改行为

 // store animationsettings in an array;
 var animationSettings = [{opacity: 0, left: '100'},{  opacity: 1 }];   
 // initialize the startup index
 var x = 1;   
 // cache selector
 var $dynamicPanel  =  $(".dynamicPanel");
 // single function
 (function animate(){
     x = x == 1 ? 0 : 1;//<--- toggle the index
     $dynamicPanel.delay(x * 5000).animate(animationSettings[x], 
        1000, 
        function () {
           animate(); // recursive call this function.
        });
 }());

<强> fiddle here

答案 3 :(得分:0)

使用SecondAnimation.apply(this)