在循环中重写代码

时间:2017-08-31 14:27:34

标签: javascript jquery loops

我只是学习JS和jQuery,所以我无法减少正常的代码如下所示:

var menuBtn = '#menu',
    classMenuOpen = 'side_menu_open',

    aboutBtn = '#about',
    classAboutOpen = 'side_about_open',

    dateBtn = '#date',
    classDateOpen = 'side_date_open',

    closeBtn = '.header__menu a, .close';

// Menu Side
$(menuBtn).on('click', function() {
  $('html').toggleClass(classMenuOpen);
});
$(closeBtn).not(menuBtn).on('click', function() {
  $('html').removeClass(classMenuOpen);
});

// About Side
$(aboutBtn).on('click', function() {
  $('html').toggleClass(classAboutOpen);
});
$(closeBtn).not(aboutBtn).on('click', function() {
  $('html').removeClass(classAboutOpen);
});

// Date Side
$(dateBtn).on('click', function() {
  $('html').toggleClass(classDateOpen);
});
$(closeBtn).not(dateBtn).on('click', function() {
  $('html').removeClass(classDateOpen);
});

我想写一个循环(下面的例子),但知识还不够。我希望有人能提前帮助,谢谢;)

['menu', 'about', 'date'].forEach((selector) => {
  $('.' + selector + ' .scrollbar-inner').scrollbar({
    onScroll: function(y, x){
      $('.' + selector + ' .scrollbar-inner').toggleClass('scroll-shadow', y.scroll >= 5);
    }
  });
});

2 个答案:

答案 0 :(得分:0)

这是您正在寻找的循环!

forEach()循环中,您循环遍历字符串数组,组件包含字符串元素(因此'menu''about'等等......)。然后在循环体内设置两个变量:

  1. selector是选择器字符串

  2. classOpen是与组件关联的元素的类名

  3. 然后你基本上只使用这两个变量编写相同的代码,而不是用设置字符串编写代码三次。

    let closeBtn = '.header__menu a, .close'
    
    ['menu', 'about', 'date'].forEach(function(component) {
      let selector = '#' + component;
      let classOpen = '.side_' + component + '_open';
    
      $(selector).on('click', function() {
        $('html').toggleClass(classOpen);
      });
    
      $(closeBtn).not(selector).on('click', function() {
        $('html').removeClass(selector);
      });
    
    });

答案 1 :(得分:0)

可能是这样的:

// wrap in IIFE for scope containment
(function($) {
  // Setup button keys
  const buttons = ['menu', 'about', 'date'];
  // click handler
  const createClickHandler = value => {
    // set loop variables
    let selector = `#${value}`
    ,   className = `side_${value}_open`;
    // create event triggers
    $(selector).on('click', e => $('html').toggleClass(className));
    $('.header__menu a, .close').not(selector).on('click', e => $('html').removeClass(className))
  };
  // iterate keys and apply handler method
  buttons.forEach(createClickHandler);

})(jQuery);