单击时添加活动类以进行分页

时间:2017-03-04 15:56:37

标签: javascript

在我的幻灯片中,我想在点击时为每个分页按钮添加和删除一个活动类。我怎么能用本机JS做到这一点。到目前为止我的代码:

//Pagination
  var p = document.getElementById('pagination');
  var phtml = '';

  for(var i = 0; i < slides.length; i++) {
    phtml+='<button>' + (i+1) + '</button>';
  }

  p.innerHTML = phtml; // create the pagination buttons

  var pbuttons = p.querySelectorAll('button'); // grab all the buttons

  for(var i = 0; i < pbuttons.length; i++) {
    pbuttons[i].onclick = (function(n) {
    pbuttons[i].classList.toggle('active');

      return function(){
        pauseSlideshow();
        goToSlide(n);
      };

    })(i);
  }

1 个答案:

答案 0 :(得分:0)

试试这个:

//Pagination
  var p = document.getElementById('pagination');
  var phtml = '';

  for(var i = 0; i < slides.length; i++) {
    phtml+='<button>' + (i+1) + '</button>';
  }

  p.innerHTML = phtml; // create the pagination buttons

  var pbuttons = p.querySelectorAll('button'); // grab all the buttons
  var activeButton = null; // ref to active button

  for(var i = 0; i < pbuttons.length; i++) {
    pbuttons[i].onclick = (function(n) {

      return function(){
        if(activeButton)
            // delete class from old active button
            activeButton.classList.remove('active');

        // change ref, this is current button
        activeButton = this;
        // add class for new 
        activeButton.classList.add('active');
        pauseSlideshow();
        goToSlide(n);
      };
    })(i);
  }

说明:
我们创建了变量存储ref到活动分页按钮。点击后,我们从旧的活动按钮中移除了类active,并将ref更改为按钮,点击了事件,然后我们将类active添加到更新的活动按钮