有没有办法将回调附加到每个语句?

时间:2014-01-08 20:13:37

标签: jquery ajax jquery-callback

我有一组五个元素,单击时:按顺序消失,加载与单击哪个元素相关的新背景图像然后交叉淡入到新背景。

我正在尝试通过ajax加载新背景时注入新内容。问题是它循环遍历所有5个元素并且在其他时间触发函数4,而不是单击的一个元素。

<script>

    $('.actor-img').click(function(e) {
    e.preventDefault();

            // First remove a 'selected' class from all elements with this class name
         $('.actor-img').removeClass('selected');

            // Add 'selected' class to the one that was clicked
        $(this).addClass('selected');

            // Loop thru all the elements w/ this class name
            // The variable 'v' will represent the actual element in each loop
        $('.actor-img').each(function(i,v) {

                // If this element doesn't have 'selected' class, hide it
             if(!$(v).hasClass('selected')) {

                    // hide it!
                    $(v).hide();

                    // or, to fade out, comment out the above and uncomment below
                     $(v).fadeOut('slow',function(){$('.page-section').load('tail_one_frame_one.html');});

                 var paras = $('.actor-img'),
                         i = 0;

                    // If using jQuery 1.4, you don't need to do || [].
                     (function() {
                      $(paras[i++] || []).fadeOut('slow', arguments.callee);
                     })();



                // This item IS selected, so change the background accordingly 
                 } else {

                    // the NEW bg class was stored in the div as data-bg
                    // get it, and save as newClassName
                    var newClassName = $(v).attr('data-bg');

                    // First reset to just .page-section-img
                    // Then add the new class (to change the background)
                 $('.page-section-img').attr('class','page-section-img').addClass(newClassName);

                 }


             });

     });

</script>

1 个答案:

答案 0 :(得分:0)

我会做以下递归功能。

希望有所帮助。

var elements = $('.actor-img');
elementIndex = 0;

fadeElements(elements[elementIndex]);

var fadeElements = function(element) {
    $(element).fadeOut('slow', function() { 
        if (elementIndex++ < elements.length - 1) {           
            fadeElements(elements[elementIndex]; 
        }
    });
};