简体   繁体   English

在页面中多次使用时,JQuery插件无法正常工作

[英]JQuery plugin not working when used multiple times in a page

I am trying to write a JQuery plugin called grid2carousel which takes some content in a Bootstrap-style grid on desktop devices and becomes a carousel on smaller screens. 我正在尝试编写一个名为grid2carousel的JQuery插件,该插件在桌面设备上的Bootstrap样式网格中获取一些内容,并在较小的屏幕上成为旋转木马。

The plugin works fine if it is the only instance of it on a page but runs into some problems if there are more than one. 如果插件是页面上唯一的实例,但如果有多个插件则会遇到一些问题。 I have created a Codepen here to demonstrate the issue: 我在这里创建了一个Codepen来演示这个问题:

http://codepen.io/decodedcreative/pen/BzdBpb http://codepen.io/decodedcreative/pen/BzdBpb

Try commenting out one of the components in the HTML section of the codepen, resizing the browser til it becomes a carousel, and then repeating this process again with it uncommented 尝试注释掉codepen的HTML部分中的一个组件,调整浏览器的大小,直到它成为轮播,然后再次重复此过程并取消注释

The plugin works by running an internal function called SetupPlugin every time the browser width is below a breakpoint specified in a data attribute in the HTML. 每当浏览器宽度低于HTML中数据属性中指定的断点时,插件就会运行一个名为SetupPlugin的内部函数。 If the browser width exceeds this breakpoint a function called DestroyPlugin reverts the HTML back to its original state. 如果浏览器宽度超过此断点,则称为DestroyPlugin的函数会将HTML恢复为其原始状态。 Like so: 像这样:

        checkDeviceState = function(){
            if($(window).width()>breakpointValue){
                destroyPlugin();
            }else{
                if(!$element.hasClass('loaded')){
                    setupPlugin();
                }
            }
        },

Below is my plugin code in its entirety. 以下是我的插件代码。 Could someone give me a pointer as to what I'm doing wrong here? 有人能给我一个关于我在这里做错了什么的指针吗?

(function (window, $){
$.grid2Carousel = function (node, options){
    var
    options = $.extend({slidesSelector: '.g2c-slides', buttonsSelector: '.g2c-controls .arrow'}, {},options),
    $element = $(node),
    elementHeight = 0,
    $slides = $element.find(options.slidesSelector).children(),
    $buttons = $element.find(options.buttonsSelector),
    noOfItems = $element.children().length + 1,
    breakpoint = $element.data("bp"),
    breakpointValue = 0;

    switch(breakpoint){
        case "sm":
            breakpointValue = 767;
            break;
        case "md":
            breakpointValue = 991;
            break;
        case "lg":
            breakpointValue = 1199;
            break;
    }

    setupPlugin = function(){

        // Add loaded CSS class to parent element which adds styles to turn grid layout into carousel layout
        $element.addClass("loaded");

        // Get the height of the tallest child element
        elementHeight = getTallestInCollection($slides)

        // As the carousel slides are stacked on top of each other with absolute positioning, the carousel doesn't have a height. Set its height using JS to the height of the tallest item;
        $element.height(elementHeight);

        // Add active class to the first slide
        $slides.first().addClass('active');


        $buttons.on("click", changeSlide);

    },

    destroyPlugin =  function(){
        $element.removeClass("loaded");
        $element.height("auto");
        $buttons.off("click");
        $slides.removeClass("active");
    },

    checkDeviceState = function(){
        if($(window).width()>breakpointValue){
            destroyPlugin();
        }else{
            if(!$element.hasClass('loaded')){
                setupPlugin();
            }
        }
    },

    changeSlide = function(){
        var $activeSlide = $slides.filter(".active"),
            $nextActive = null,
            prevSlideNo = $activeSlide.prev().index() + 1,
            nextSlideNo = $activeSlide.next().index() + 1;

        if($(this).hasClass('left')){


            if(prevSlideNo !== 0){
                $nextActive = $activeSlide.prev();
                $nextActive.addClass('active');
                $slides.filter(".active").not($nextActive).removeClass("active");
            }else{
                $nextActive = $slides.last();
                $nextActive.addClass('active');
                $slides.filter(".active").not($nextActive).removeClass("active");
            }

        }else if($(this).hasClass('right')){


            if(nextSlideNo !== 0){
                $nextActive = $activeSlide.next();
                $nextActive.addClass('active');
                $slides.filter(".active").not($nextActive).removeClass("active");
            }else{
                $nextActive = $slides.first();
                $nextActive.addClass('active');
                $slides.filter(".active").not($nextActive).removeClass("active");
            }

        }
    },

    getTallestInCollection = function(collection){

        $(collection).each(function(){
            if($(this).outerHeight() > elementHeight){
                elementHeight = $(this).outerHeight();
            }
        });

        return elementHeight;

    };

    setupPlugin();
    checkDeviceState();
    $(window).on("resize", checkDeviceState);

}




$.fn.grid2Carousel = function (options) {
    this.each( function (index, node) {
        $.grid2Carousel(node, options)
    });

    return this
}
})(window, jQuery);

Many thanks, 非常感谢,

James 詹姆士

Please check line #30 in your plugin code,it looks that you've just forget to add var keyword so instead of creating local variables to store functions setupPlugin, destoryPlugin and so on you've created global variables and then each new initialization of your plugin is rewriting this functions to point to a newly created slider. 请查看插件代码中的第30行,它看起来你只是忘记添加var关键字而不是创建局部变量来存储函数setupPlugin,destoryPlugin等等你已经创建了全局变量然后每个新的初始化你的插件正在重写此函数以指向新创建的滑块。

setupPlugin = function(){

should be 应该

var setupPlugin = function(){

Updated code here . 这里更新了代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在单个页面中的多个位置使用时,JQuery插件无法正常工作 - JQuery plugin not working when used in multiple places in a single page 在通过AJAX包含另一个页面的页面上使用时,JQuery验证插件不起作用 - JQuery Validation Plugin not working when used on page that includes another page via AJAX 创建一个jQuery插件,该插件在同一页面上多次实施时存在问题 - creating a jQuery plugin having issues with when implemented multiple times on the same page jQuery变量定义了多次:用于事件和页面加载时 - jQuery variable is defined multiple times: for events and when the page loads 当我在同一页面中多次使用滑块时,滑块不起作用 - slider is not working when I use it multiple times in the same page asmselect jquery插件-多次选择选项 - asmselect jquery plugin - selecting option multiple times jQuery插件公共方法应用于多个元素时不起作用 - jQuery Plugin public methods not working when applied to multiple elements Jquery表单验证不起作用,没有使用插件 - Jquery form validation not working no plugin used 遮罩图像多次使用时不显示 - Mask images not displaying when used multiple times 多次使用该类时,jQuery hoverIntent仅适用于一个div类 - jQuery hoverIntent for only one div class when the class is being used multiple times
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM