简体   繁体   English

为什么滑块循环时addClass和removeClass不再起作用?

[英]Why does addClass and removeClass no longer work when slider loops?

I have a carousel slider that has 4 circles underneath it to notify the user when a particular slider is being displayed. 我有一个旋转木马滑块,其下方有4个圆圈,以便在显示特定滑块时通知用户。 To do that, I add and remove classes depending on the index. 为此,我根据索引添加和删除类。

This code works for me the first time around, but then stops working once the carousel loops again back to index 0. I know that the code is working because all my console logs show up in my console. 这段代码对我来说是第一次工作,但是一旦轮播再次循环回到索引0,它便停止工作。我知道代码正在工作,因为我的所有控制台日志都显示在控制台中。 So the loop is definitely happening. 因此,循环肯定正在发生。 The problem is that my jQuery code stops adding and removing classes once the slider loops. 问题是,一旦滑块循环,我的jQuery代码就会停止添加和删除类。

How can I make the addClass and removeClass methods in jQuery keep working once the slider loops back to index 0? 一旦滑块循环回到索引0,如何使jQuery中的addClass和removeClass方法继续工作?

  <div style="display: inline-block;">
      <div class="greenCircle carouselCircle"></div>
      <div class="greyCircle2 greenCircle2 carouselCircle"></div>
      <div class="greyCircle3 greenCircle3 carouselCircle"></div>
      <div class="greyCircle4 greenCircle4 carouselCircle"></div>
    </div>

$(document).ready(function() {

if (index === 0){
  $(".carouselCircle").removeClass("greenCircle4");
  $(".carouselCircle").addClass("greyCircle4");
     console.log("ahoy I am index 0");


}

  else if(index === 1){
    $(".carouselCircle").removeClass("greenCircle");
    $(".carouselCircle").addClass("greyCircle");
     $(".carouselCircle").removeClass("greyCircle2");
      console.log("ahoy I am index 1");
    }

    else if(index === 2){
    $(".carouselCircle").removeClass("greyCircle3");
    $(".carouselCircle").addClass("greyCircle2");
       console.log("ahoy I am index 2");

    }

     else if(index === 3){
    $(".carouselCircle").removeClass("greyCircle4");
    $(".carouselCircle").addClass("greyCircle3");
     $(".carouselCircle").removeClass("greyCircle");
     $(".carouselCircle").addClass("greenCircle");
     console.log("Ahoy I am index 3");
    }

});

The following is the loop code, where I injected my jQuery into. 以下是循环代码,我在其中注入了jQuery。 It is a bit long so this is only if you have to know all the particulars. 它有点长,所以仅在您必须了解所有详细信息时才这样。

    /**
    * Wallop.js
    *
    * @fileoverview Minimal JS library to show & hide things
    *
    * @author Pedro Duarte
    * @author http://pedroduarte.me/wallop
    *
    */
    (function(global){
      function Wallop(selector, options) {
        if (!selector) { throw new Error('Missing selector. Refer to Usage documentation: https://github.com/peduarte/wallop#javascript'); }

        for (var i = 0; i < selectorPool.length; i++) {
          if (selectorPool[i] === selector) {
            throw new Error('An instance of Wallop with this selector already exists.');
          }
        }

        this.options = {
          buttonPreviousClass: 'Wallop-buttonPrevious',
          buttonNextClass: 'Wallop-buttonNext',
          itemClass: 'Wallop-item',
          currentItemClass: 'Wallop-item--current',
          showPreviousClass: 'Wallop-item--showPrevious',
          showNextClass: 'Wallop-item--showNext',
          hidePreviousClass: 'Wallop-item--hidePrevious',
          hideNextClass: 'Wallop-item--hideNext',
          carousel: true
        };

        // Whitelist elements which contain `length`
        this.whitelist = {
          'form': true
        };

        if (selector.length > 0 && !this.whitelist[selector]) {
          throw new Error('Selector cannot be an array, Refer to Usage documentation: https://github.com/peduarte/wallop#javascript');
        } else {
          this.$selector = selector;
        }

        this.options = extend(this.options, options);
        this.event = null;

        // "Global vars"
        this.reset();
        this.buttonPrevious = this.$selector.querySelector(' .' + this.options.buttonPreviousClass);
        this.buttonNext = this.$selector.querySelector(' .' + this.options.buttonNextClass);

        this.bindEvents();
        this.createCustomEvent();

        // If there is no active item, start at 0
        if (this.currentItemIndex === -1) {
          this.currentItemIndex = 0;
          addClass(this.allItemsArray[this.currentItemIndex], this.options.currentItemClass);
        }



        // Update button states to make sure the correct state is set on initialization
        this.updateButtonStates();

        // Wrapped in timeout function so event can
        // be listened from outside at anytime
        var _this = this;
        setTimeout(function() {
          _this.event.detail.currentItemIndex = _this.currentItemIndex;
          _this.$selector.dispatchEvent(_this.event);
        }, 0);
      }

      var selectorPool = [];

      var WS = Wallop.prototype;

      // Update prev/next disabled attribute
      WS.updateButtonStates = function () {
        if ((!this.buttonPrevious && !this.buttonNext) || this.options.carousel) { return; }

        if (this.currentItemIndex === this.lastItemIndex) {
          this.buttonNext.setAttribute('disabled', 'disabled');
        } else if (this.currentItemIndex === 0) {
          this.buttonPrevious.setAttribute('disabled', 'disabled');
        }
      };

      // Reset all settings by removing classes and attributes added by goTo() & updateButtonStates()
      WS.removeAllHelperSettings = function () {
        removeClass(this.allItemsArray[this.currentItemIndex], this.options.currentItemClass);
        removeClass($$(this.options.hidePreviousClass, this.$selector), this.options.hidePreviousClass);
        removeClass($$(this.options.hideNextClass, this.$selector), this.options.hideNextClass);
        removeClass($$(this.options.showPreviousClass, this.$selector), this.options.showPreviousClass);
        removeClass($$(this.options.showNextClass, this.$selector), this.options.showNextClass);

        if (!this.buttonPrevious && !this.buttonNext) { return; }

        this.buttonPrevious.removeAttribute('disabled');
        this.buttonNext.removeAttribute('disabled');
      };

      // Method to add classes to the right elements depending on the index passed
      WS.goTo = function (index) {
        if (index === this.currentItemIndex) { return; }

        // Fix the index if it's out of bounds and carousel is enabled
        index = index === -1 && this.options.carousel ? this.lastItemIndex : index;
        index = index === this.lastItemIndex + 1 && this.options.carousel ? 0 : index;

        // Exit when index is out of bounds
        if (index < 0 || index > this.lastItemIndex) { return; }

        this.removeAllHelperSettings();

        var isForwards = (index > this.currentItemIndex || index === 0 && this.currentItemIndex === this.lastItemIndex) && !(index === this.lastItemIndex && this.currentItemIndex === 0);
        addClass(this.allItemsArray[this.currentItemIndex], isForwards ? this.options.hidePreviousClass : this.options.hideNextClass);
        addClass(this.allItemsArray[index], this.options.currentItemClass + ' ' + (isForwards ? this.options.showNextClass : this.options.showPreviousClass));

        this.currentItemIndex = index;

$(document).ready(function() {

if (index === 0){
  $(".carouselCircle").removeClass("greenCircle4");
  $(".carouselCircle").addClass("greyCircle4");
     console.log("ahoy I am index 0");


}

  else if(index === 1){
    $(".carouselCircle").removeClass("greenCircle");
    $(".carouselCircle").addClass("greyCircle");
     $(".carouselCircle").removeClass("greyCircle2");
      console.log("ahoy I am index 1");
    }

    else if(index === 2){
    $(".carouselCircle").removeClass("greyCircle3");
    $(".carouselCircle").addClass("greyCircle2");
       console.log("ahoy I am index 2");

    }

     else if(index === 3){
    $(".carouselCircle").removeClass("greyCircle4");
    $(".carouselCircle").addClass("greyCircle3");
     $(".carouselCircle").removeClass("greyCircle");
     $(".carouselCircle").addClass("greenCircle");
     console.log("Ahoy I am index 3");
    }

});



    /*







        this.updateButtonStates();

        this.event.detail.currentItemIndex = this.currentItemIndex;
        this.$selector.dispatchEvent(this.event);
      };

      // Previous item handler
      WS.previous = function () {
        this.goTo(this.currentItemIndex - 1);
      };

      // Next item handler
      WS.next = function () {
        this.goTo(this.currentItemIndex + 1);
      };

      // Update global variables
      WS.reset = function () {
        this.allItemsArray = Array.prototype.slice.call(this.$selector.querySelectorAll(' .' + this.options.itemClass));
        this.currentItemIndex = this.allItemsArray.indexOf(this.$selector.querySelector(' .' + this.options.currentItemClass));
        this.lastItemIndex = this.allItemsArray.length - 1;
      };

      // Attach click handlers
      WS.bindEvents = function () {
        selectorPool.push(this.$selector);

        var _this = this;

        if (this.buttonPrevious) {
          this.buttonPrevious.addEventListener('click', function (event) {
            event.preventDefault();
            _this.previous();
          });
        }

        if (this.buttonNext) {
          this.buttonNext.addEventListener('click', function (event) {
            event.preventDefault();
            _this.next();
          });
        }

      };

      // Method to bind custom event
      WS.on = function (eventName, callback) {
        this.$selector.addEventListener(eventName, callback, false);
      };

      // Method to unbind custom event
      WS.off = function (eventName, callback) {
        this.$selector.removeEventListener(eventName, callback, false);
      };

      // Create custom Event
      WS.createCustomEvent = function () {
        var _this = this;
        this.event = new CustomEvent('change', {
          detail: {
            wallopEl: _this.$selector,
            currentItemIndex: Number(_this.currentItemIndex)
          },
          bubbles: true,
          cancelable: true
        });
      };

      // Helper functions
      function $$(element, container) {
        if (!element) { return; }
        if (!container) {
          container = document;
        }
        return container.querySelector('.' + element);
      }

      function addClass(element, className) {
        if (!element) { return; }
        element.className = (element.className + ' ' + className).trim();
      }

      function removeClass(element, className) {
        if (!element) { return; }
        element.className = element.className.replace(className, '').trim();
      }

      function extend(origOptions, userOptions){
        var extendOptions = {}, attrname;
        for (attrname in origOptions) { extendOptions[attrname] = origOptions[attrname]; }
        for (attrname in userOptions) { extendOptions[attrname] = userOptions[attrname]; }
        return extendOptions;
      }

      // Pollyfill for CustomEvent() Constructor - thanks to Internet Explorer
      // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
      function CustomEvent(event, params) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent('CustomEvent');
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
        return evt;
      }

      CustomEvent.prototype = window.CustomEvent ? window.CustomEvent.prototype : {};
      window.CustomEvent = CustomEvent;

      // Exports to multiple environments
      if(typeof define === 'function' && define.amd){ //AMD
        define(function () { return Wallop; });
      } else if (typeof module !== 'undefined' && module.exports){ //node
        module.exports = Wallop;
      } else { // browser
        // use string because of Google closure compiler ADVANCED_MODE
        /* jslint sub:true */
        global['Wallop'] = Wallop;
      }
    }(this));

I think that you are incrementing the index variable after a specific time using setInterval(callback, intervalPeriod) . 我认为您正在使用setInterval(callback, intervalPeriod)在特定时间之后递增 index变量。

The problem here is You are using the jQuery selector $(".carousalCircle") to select the Elements which selects all the circles . 这里的问题是,您正在使用jQuery选择器$(".carousalCircle")选择选择所有圆的Elements。 So, select the appropriate circles and then add/remove Class. 因此,选择适当的圈子 ,然后添加/删除班级。

Hope this hints you understood the problem. 希望这暗示您了解问题。

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

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