Кнопка «Назад» на индикаторе выполнения - PullRequest
1 голос
/ 20 апреля 2020

Я пытался создать многоэтапную структуру контента с помощью кнопки BACK & NEXT. Все работает как положено, но кнопка «Назад» не удаляет активный класс из индикатора выполнения. Может кто-нибудь, пожалуйста, взгляните на мой код и помощь.

$(document).ready(function(){
  //steps ui
  var progressBar = {
  Bar : $('#progress-bar'),
  Reset : function(){

  },
  Next: function(){
    $('#progress-bar li:not(.active):first').addClass('active');
  },
  Back: function(){
    $('#progress-bar li.active:last').removeClass('active');
  }
}

  var current = 1;

    widget      = $(".step");
    btnnext     = $(".next");
    btnback     = $(".back"); 
    btnsubmit   = $(".submit");

    // Init buttons and UI
    widget.not(':eq(0)').hide();
    hideButtons(current);
    setProgress(current);

    // Next button click action
    btnnext.click(function(){
        if(current < widget.length) {           
            widget.show();          
            widget.not(':eq('+(current++)+')').hide();
            setProgress(current); 
            //alert("I was called from btnNext");
        }       
       hideButtons(current); 
    progressBar.Next();
   });

  // Back button click action   
  btnback.click(function(){         
      if(current > 1){
            current = current - 2;
            btnnext.trigger('click');

        }
        hideButtons(current);
    progressBar.Back();
    });     
});

Прикрепив ссылку на кодовую ссылку ниже

CODEPEN

Ответы [ 2 ]

2 голосов
/ 20 апреля 2020

В вашем коде есть небольшая ошибка. Когда вы нажимаете кнопку «Назад», следующая нажатая кнопка - триггер. Пожалуйста, обновите функцию щелчка btnback следующим образом:

   $(document).ready(function() {
        //steps ui
        var progressBar = {
            Bar: $('#progress-bar'),
            Reset: function() {

            },
            Next: function() {
                $('#progress-bar li:not(.active):first').addClass('active');
            },
            Back: function() {
                $('#progress-bar li.active:last').removeClass('active');
            }
        }

        var current = 1;

        widget = $(".step");
        btnnext = $(".next");
        btnback = $(".back");
        btnsubmit = $(".submit");

        // Init buttons and UI
        widget.not(':eq(0)').hide();
        hideButtons(current);
        setProgress(current);

        // Next button click action
        btnnext.click(function() {
            if (current < widget.length) {
                widget.show();
                widget.not(':eq(' + (current++) + ')').hide();
                setProgress(current);
                //alert("I was called from btnNext");
            }
            hideButtons(current);
            progressBar.Next();
        });

        // Back button click action     
        btnback.click(function(event) {
            var divShowCount = 0
            if (current > 1) {
                current = current - 1;
                divShowCount = current - 1
            }
            widget.show();
            widget.not(':eq(' + (divShowCount) + ')').hide();
            hideButtons(current);
            progressBar.Back();
        });
    });

    // Change progress bar action
    setProgress = function(currstep) {
        var percent = parseFloat(100 / widget.length) * currstep;
        percent = percent.toFixed();
        $(".progress-bar")
            .css("width", percent + "%")
            .html(percent + "%");
    }


    // Hide buttons according to the current step
    hideButtons = function(current) {
        var limit = parseInt(widget.length);
        $(".action").hide();
        if (current < limit)
            btnnext.show();
        if (current > 1) btnback.show();
        if (current == limit) {
            btnnext.hide();
            btnsubmit.show();
        }
    }

Надеюсь, это поможет вам

0 голосов
/ 20 апреля 2020

... но кнопка "Назад" не удаляет активный класс из индикатора выполнения.

В вашем коде есть ошибка logi c:

$(document).ready(function(){
  //steps ui
  var progressBar = {
  Bar : $('#progress-bar'),
  Reset : function(){
    
  },
  Next: function(){
    $('#progress-bar li:not(.active):first').addClass('active');
  },
  Back: function(){
    $('#progress-bar li.active:last').removeClass('active');
  }
}
  
  var current = 1;
	
	widget      = $(".step");
	btnnext     = $(".next");
	btnback     = $(".back"); 
	btnsubmit   = $(".submit");

	// Init buttons and UI
	widget.not(':eq(0)').hide();
	hideButtons(current);
	setProgress(current);

	// Next button click action
	btnnext.click(function(){
	    if(current < widget.length) { 			
            widget.show(); 			
            widget.not(':eq('+(current++)+')').hide();
  	        setProgress(current); 
            //alert("I was called from btnNext");
        } 		
       hideButtons(current); 
    progressBar.Next();
   });
   
  // Back button click action 	
  btnback.click(function(){ 		
      if(current > 1){
		    current = current - 2;
		    //btnnext.trigger('click'); why do you need this?
        
	    }else{ //added an else here so the button hides only at the beginning step
        hideButtons(current);
      }
        //hideButtons(current);
    progressBar.Back();
    });		
});

// Change progress bar action
setProgress = function(currstep){
	var percent = parseFloat(100 / widget.length) * currstep;
	percent = percent.toFixed();
	$(".progress-bar")
        .css("width",percent+"%")
        .html(percent+"%");		
}


// Hide buttons according to the current step
hideButtons = function(current){
	var limit = parseInt(widget.length); 

	$(".action").hide();

	if(current < limit) btnnext.show(); 	
  if(current > 1) btnback.show();
	if(current == limit) { btnnext.hide(); btnsubmit.show(); }
}
 .step-container > div {
  height:auto;
  padding:20px;
   background: #ccc
}

.progressbar {
      margin:20px;
      counter-reset: step; 
  }
  .progressbar li {
      list-style-type: none;
      width: 25%;
      float: left;
      font-size: 12px;
      position: relative;
      text-align: center;
      text-transform: uppercase;
      color: #7d7d7d;
  }
  .progressbar li:before {
      width: 15px;
      height: 15px;
      content: '';
      line-height: 30px;
      border: 2px solid #7d7d7d;
      background-color: #7d7d7d;
      display: block;
      text-align: center;
      margin: 0 auto 10px auto;
      border-radius: 50%;
      transition: all .8s;
  }
  .progressbar li:after {
      width: 100%;
      height: 2px;
      content: '';
      position: absolute;
      background-color: #7d7d7d;
      top: 7px;
      left: -50%;
      z-index: -1;
      transition: all .8s;
  }
  .progressbar li:first-child:after {
      content: none;
  }
  .progressbar li.active:before {
      border-color: #55b776;
      background-color: #55b776;
      transition: all .8s;
  }
  .progressbar li.active:after {
      background-color: #55b776;
      transition: all .8s;
  }

.btn {
  background-color: #55b776;
  margin: 5px;
  width: 75px;
  color: white;
}
.btn:hover {
  color: white; 
}
.btn:focus {
  color: white;
}
.btn-container {
  display: flex;
  justify-content: center;
  width: 100%;
  position: absolute;
  bottom: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container p-5">
	<div class="row">
        <div class="col-md-12 step-container">
    	    
            <div class="step">Step 1</div>
            <div class="step">Step 2</div>
            <div class="step">Step 3</div>
            <div class="step">Step 4</div>
          
          
        </div>
	</div>
</div>
<div class="container p-5">
            <div class="row">
              <div class="col-lg-9 p-4">
            <ul id="progress-bar" class="progressbar">
           <li class="active">Step 1</li>
           <li>Step 2</li>
           <li>Step 3</li>
           <li>Step 4</li>
        </ul>
              </div>
              <div class="col-lg-3" style="padding:20px">
            <button class="action back">Back</button>
            <button class="action next">Next</button>
            <button class="action submit btn btn-success">Submit</button>
              </div>
          </div>
            </div>

Я добавил еще одно, чтобы кнопка скрывалась только на начальном этапе, и удалил событие триггера

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...