【问题标题】:Call a function, passed to another function as an argument, on a jQuery object在 jQuery 对象上调用一个函数,作为参数传递给另一个函数
【发布时间】:2016-06-15 14:31:39
【问题描述】:

我正在使用另一个 Stack Overflow 帖子中的 this answer 来让多个元素使用 fadeIn 方法一次淡入一个,并使用 fadeOut 反向淡出。例如,使用fadeIn:

$("#container").children().each(function(index) {
    $(this).delay(400 * index).fadeIn(300);
});

由于我将多次使用代码并使用不同的动画,因此我将其放入一个函数中,其中要迭代的 jQuery 对象、延迟和要执行的动画作为参数传递:

function animateOneByOne(elements, delay, animation) {
    elements.each(function(index) {
        $(this).delay(delay*index).animation();
    });
}

使用类似的方式调用:

animateOneByOne($("#introelements").children(), 400, function() { fadeIn(300); });

我现在意识到这不起作用,因为$(...).delay(...) 对象内没有animation 函数。

有没有一种很好的方法可以将此代码放入函数中?

【问题讨论】:

    标签: javascript jquery function parameter-passing


    【解决方案1】:

    在写这个问题时,我找到了一个简单的解决方案,我将作为参数传递的函数更改为将单个元素作为参数:

    function animateOneByOne(elements, delay, animation) {
        elements.each(function(index) {
            animation($(this).delay(delay * index));
        });
    }
    

    使用类似的方式调用:

    animateOneByOne($("#introelements").children(), 400, function(element) { element.fadeIn(300); });
    

    (我已经发布了这个,以防其他人有类似的问题,并以防有更好的解决方案。)

    【讨论】:

      猜你喜欢
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      相关资源
      最近更新 更多