0

如何使功能extra_stuffanimdisplay_effects功能完成后执行?最好的选择是保留函数extra_stuff直到animate完成,因为我不想编辑传递给on方法的匿名函数,它应该保持简单和可读。

<html>
    <head>
        <meta charset="utf-8">
        <script src="jquery-2.0.3.min.js"></script>
        <style>
            .selected {color:pink;}
        </style>
    </head>
    <body>

        <ul id="workers">
            <li><a href="#">worker#1</a></li>
            <li><a href="#">worker#2</a></li>
            <li><a href="#">worker#3</a></li>
            <li><a href="#">worker#4</a></li>
        </ul>

        <script>

        $(function()
        {
            function unmark_selected()
            {
                $('.selected').removeClass('selected');
            }
            function mark_user(e)
            {
                e.addClass('selected');
            }

            function display_effects(e)
            {
                e.animate({ fontSize: "24px" }, 1500);
            }

            function extra_stuff()
            {
                console.log('maybe another animation');
            }

            $('ul#workers li a').on('click', function()
            {
                unmark_selected();
                mark_user( $(this) );
                display_effects( $(this) );
                extra_stuff();
            });
        });

        </script>       
    </body>
</html>
4

2 回答 2

2

makedisplay_effects返回一个promise()对象,然后在promise的回调中调用extra_stuff方法done

$(function () {
    function unmark_selected() {
        $('.selected').removeClass('selected');
    }

    function mark_user(e) {
        e.addClass('selected');
    }

    function display_effects(e) {
        return e.animate({
            fontSize: "24px"
        }, 1500).promise();
    }

    function extra_stuff() {
        console.log('maybe another animation');
    }

    $('ul#workers li a').on('click', function () {
        unmark_selected();
        mark_user($(this));
        display_effects($(this)).done(extra_stuff);
    });
});
于 2013-10-04T09:54:29.160 回答
1

You need a callback:

function display_effects(e, callback) {
    e.animate({ fontSize: "24px" }, 1500, callback);
}

$('ul#workers li a').on('click', function() {
    unmark_selected();
    mark_user( $(this) );
    display_effects( $(this), extra_stuff ); // no invocation, pass reference!
});

It will be called in the future, when the fontsize animation is done. Check the docs for the .animate() method. Notice that if you simply want to add another animation after the fontsize, they will be queued automatically.

于 2013-10-04T09:55:49.970 回答