简体   繁体   中英

Call a function, passed to another function as an argument, on a jQuery object

I was using this answer from another Stack Overflow post to have multiple elements fade in one at a time using the fadeIn method and fade out in reverse using fadeOut . For example, using fadeIn :

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

Since I would be using the code multiple times and with different animations, I put it into a function, where the jQuery object to iterate over, delay and animation to perform are passed as arguments:

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

called using something like:

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

I've now realised this doesn't work because there is no animation function inside the $(...).delay(...) object.

Is there a nice way of putting this code into a function?

While writing the question I found a simple solution, in which I changed the function passed as an argument to have the single element as a parameter:

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

called using something like:

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

(I've posted this in case anyone else had a similar problem and in case there are any better solutions.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM