简体   繁体   中英

jQuery merge functions for different selectors

I have a short script that changes a few classes on doc ready, i run this script for two different selectors, the script is identical so was wondering if there is a way i can compact it into shorter code?

jQuery(document).ready(function($){

    var list1 = $('#slides .links li');
    $(list1).filter(':first').addClass('active');

    setInterval(function() {
        if( $(list1).filter('.active').index() !== $(list1).length - 1 ) {
            $(list1).filter('.active').removeClass('active').next().addClass('active');
        }
        else {
            $(list1).removeClass('active').filter(':first').addClass('active');
        }
    }, 4000);

    var list2 = $('#slides .pics li');
    $(list2).filter(':first').addClass('active');

    setInterval(function() {
        if( $(list2).filter('.active').index() !== $(list2).length - 1 ) {
            $(list2).filter('.active').removeClass('active').next().addClass('active');
        }
        else {
            $(list2).removeClass('active').filter(':first').addClass('active');
        }
    }, 4000);
});

If there is a name for the method someone would use to compress this I will look it up and have a go at re-writing. Many thanks.

Try to create a common function for that and call it individually,

function timer(list) {
  list.filter(':first').addClass('active');
  setInterval(function() {
        if(list.filter('.active').index() !== list.length - 1 ) {
            list.filter('.active').removeClass('active').next().addClass('active');
        }
        else {
            list.removeClass('active').filter(':first').addClass('active');
        }
  }, 4000);
}

timer($('#slides .links li'));
timer($('#slides .pics li'));

Since each list has a :first, I would do

$(function() {

  var $list = [$('#slides .links li),$('#slides .pics li')];
  $list.each(function() { this.filter(':first').addClass('active')});

  setInterval(function() {
    $list.each(function() {
      if(this.filter('.active').index() !== this.length - 1 ) {
        this.filter('.active').removeClass('active').next().addClass('active');
      }
      else {
       this.removeClass('active').filter(':first').addClass('active');
      }
    });
  }, 4000);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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