自定义jQuery插件在多次调用时覆盖以前的数据

时间:2014-04-03 11:00:12

标签: javascript jquery arrays jquery-plugins

我已经编写了一个自定义jQuery carousel插件,其代码如下:

(function( $ ) {
var carouselFunctions = {
    'init' : function( options ) {

        // Set some default options
        var settings = $.extend({
            'width' : false,
            'height' : 200,
            'currentSlide' : false,
            'slideTime' : false,
        }, options);

        // Return each matched element
        return this.each(function() {
            // Create an Array for the Slides
            slideArray = new Array();

            // Loop through and add the slides
            $(' > div', this).each(function() {
                // Add the Slide
                slideArray.push($(this));
            });

            // Wrap it in a Holder
            $(this).addClass('ui-carousel');

            // Determine the Carousel Width
            if (settings.width == false) {
                var cWidth = $(this).outerWidth();
            } else {
                var cWidth = settings.width;
            }

            // Create the Carousel Buttons
            var prevButton = $('<a href="#" class="left prev ui-button ui-icon ui-icon-chevron-left"></a>');
            var nextButton = $('<a href="#" class="right next ui-button ui-icon ui-icon-chevron-right"></a>');

            // Create the Carousel Navigation
            var carouselNav = $('<div class="ui-carousel-navigation"></div>').css({
                'width' : cWidth,
                'margin-top' : (settings.height / 2) - 7,
                'position' : 'absolute'
            });

            // Add the Carousel Buttons
            carouselNav.append(prevButton).append(nextButton);

            // Add the Navigation to the Carousel
            $(this).append(carouselNav);

            // Create the Inner Div
            var carouselInner = $('<div class="ui-carousel-inner"></div>');

            // Set the CSS
            carouselInner.css({
                'width' : (cWidth * slideArray.length),
                'height' : settings.height
            });

            // Add the Inner Container to the Carousel
            $(this).append(carouselInner);

            // Append the Slides
            for (var i in slideArray)
            {
                // Append to the Inner
                slideArray[i].css({
                    'width' : cWidth,
                    'min-height' : settings.height,
                    'vertical-align' : 'top',
                    'display' : 'inline-block'
                }).appendTo(carouselInner);
            }

            // Set the Current and total Slides
            var currentSlide = 0;
            var nextSlide = currentSlide + 1;
            var prevSlide = slideArray.length - 1;
            var totalSlides = slideArray.length;

            // Check whether we have a slide specified
            if (currentSlide !== false)
            {
                // Loop through and Find the Slide
                for (var i in slideArray)
                {
                    // Check the IDs
                    if (currentSlide == slideArray[i].attr('id'))
                    {
                        // Set the Slide Index
                        currentSlide = i;

                        // Set the Next Slide
                        nextSlide = (currentSlide == (totalSlides.length - 1)) ? 0 : i + 1;

                        // Set the Previous Slide
                        prevSlide = (currentSlide == 0) ? slideArray.length - 1 : i - 1;
                    }
                }
            }

            // Blank Interval
            leftInterval = false;

            // Function for Sliding Left
            slideLeft = function() {
                // Set the Margins and Append the Previous Slide to the Array
                slideArray[prevSlide].css('margin-left', 0).appendTo(carouselInner);
                slideArray[nextSlide].css('margin-left', 0);

                // Animate the Slide
                slideArray[currentSlide].animate({ 'margin-left' : -cWidth }, function() {
                    // Increment the Current Slide
                    currentSlide++;

                    // Go to the Beginning Slide if necessary
                    currentSlide = (currentSlide == totalSlides) ? 0 : currentSlide;

                    // Set the Previous and Next Slide
                    prevSlide = ((currentSlide - 1) < 0) ? totalSlides - 1 : currentSlide - 1;
                    nextSlide = ((currentSlide + 1) >= totalSlides) ? 0 : currentSlide + 1;

                    // If we have a Slide Time Specified
                    if (settings.slideTime !== false)
                    {
                        // Clear the Animation Interval
                        window.clearInterval(leftInterval);

                        // Reset the Animation Interval
                        leftInterval = window.setInterval(slideLeft, settings.slideTime);
                    }
                });
            }

            // Function for Sliding Right
            slideRight = function() {
                // Animate the Slide
                slideArray[prevSlide].animate({ 'margin-left' : 0 }, function() {
                    // Move the next slide in place
                    slideArray[nextSlide].css('margin-left', -cWidth).insertBefore(slideArray[prevSlide]);

                    // Decrement the Current Slide
                    currentSlide--;

                    // Go to the End Slide if necessary
                    currentSlide = (currentSlide < 0) ? totalSlides - 1 : currentSlide;

                    // Set the Previous and Next Slide
                    prevSlide = ((currentSlide - 1) < 0) ? totalSlides - 1 : currentSlide - 1;
                    nextSlide = ((currentSlide + 1) >= totalSlides) ? 0 : currentSlide + 1;

                    // If we have a Slide Time Specified
                    if (settings.slideTime !== false)
                    {
                        // Clear the Animation Interval
                        window.clearInterval(leftInterval);

                        // Reset the Animation Interval
                        leftInterval = window.setInterval(slideLeft, settings.slideTime);
                    }
                });
            }

            // Set the Next Function
            nextButton.click(function(e) {
                // Prevent Default Behaviour
                e.preventDefault();

                // Add the Slide Behaviour
                slideLeft();
            });

            // Set the Previous Function
            prevButton.click(function(e) {
                // Prevent Default Behaviour
                e.preventDefault();

                // Add the Slide Behaviour
                slideRight();
            });

            // Set the Initial Timer
            if (settings.slideTime !== false)
            {
                // Set the Slide on a Timer
                leftInterval = window.setInterval(slideLeft, settings.slideTime);
            }
        });
    }
};
$.fn.carousel = function( method ) {
    // Method calling logic
    if ( carouselFunctions[ method ] ) {
        return carouselFunctions[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
        return carouselFunctions.init.apply( this, arguments );
    } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.carousel' );
    }
};
})( jQuery );

这个插件在调用一次时效果很好,但是如果我多次调用它,那么slideArray似乎会被覆盖。

例如,在包含以下代码的页面上:

<div id="carousel1">
    <div>Slide 1</div>
    <div>Slide 2</div>
</div>
<script type="text/javascript">
    $('#carousel1').carousel();
</script>
<div id="carousel2">
    <div>Slide 3</div>
    <div>Slide 4</div>
    <div>Slide 5</div>
</div>
<script type="text/javascript">
    $('#carousel2').carousel();
</script>

当我点击carousel1的滚动按钮时,幻灯片功能会在carousel2上执行。我在幻灯片按钮的click事件上做了一个快速的console.log,以显示slideArray的元素,并且看起来来自carousel1的slideArray被来自carousel2的slideArray覆盖。

我该如何解决这个问题?

0 个答案:

没有答案