javascript 常见问题 - 使用ES6类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 常见问题 - 使用ES6类相关的知识,希望对你有一定的参考价值。

/**
 * Opens and closes FAQs.
 *
 */
export class Faq {
  /**
  * Constructor.
  */
  constructor() {
    /**
     * Opens and closes FAQs.
     *
     */
    class FaqAnswer {
      /**
      * Constructor.
      * @param {Node} trigger - The FAQ trigger
      * @param {Function} closeOthers - The close all others function
      */
      constructor(trigger, closeOthers) {
        this.trigger = trigger;
        this.closeOthers = closeOthers;
        this.svg = trigger.querySelector('[data-js-faq-svg]');
        this.answer = trigger.querySelector('[data-js-faq-answer]');
        this.answerActiveClass = 'faqs__faq-answer--active';
        this.svgActiveClass = 'faqs__faq-svg--active';
        this.activeState = false;

        trigger.addEventListener('click', event => this.toggleFaq(event));
      }

      /**
       * Opens the Faq
       */
      open() {
        this.closeOthers(this);
        this.answer.classList.add(this.answerActiveClass);
        this.svg.classList.add(this.svgActiveClass);
        this.activeState = true;
      }

      /**
       * Close the Faq
       */
      close() {
        this.answer.classList.remove(this.answerActiveClass);
        this.svg.classList.remove(this.svgActiveClass);
        this.activeState = false;
      }

      /**
       * Toggle the Faq
       * @param {event} event - Prevents the default action of the trigger
       */
      toggleFaq(event) {
        event.preventDefault();
        if (this.activeState === false) {
          this.open();
        } else {
          this.close();
        }
      }
    }

    const triggers = document.querySelectorAll('[data-js-faq-trigger]');
    this.answers = [];

    for (let index = 0; index < triggers.length; index++) {
      const trigger = triggers[index];
      const answer = new FaqAnswer(trigger, activeAnswer => this.closeOthers(activeAnswer));
      this.answers.push(answer);
    }
  }

  /**
   * Close all other FAQs
   * @param {FaqAnswer} activeAnswer - The active FAQ
   */
  closeOthers(activeAnswer) {
    this.answers.forEach(answer => {
      if (answer !== activeAnswer) {
        answer.close();
      }
    });
  }
}

以上是关于javascript 常见问题 - 使用ES6类的主要内容,如果未能解决你的问题,请参考以下文章

javascript JavaScript滚动到ID - 使用ES6类

javascript 返回顶部 - 使用ES6类

JavaScript高级class类ES6实现继承ES6对象增强

JavaScript高级class类ES6实现继承ES6对象增强

如何从 ES6 JavaScript 类实例中获取源代码位置?

类函数中的 Javascript ES6 承诺