execute functions by pressing enter

1

I try to execute different actions by pressing enter. But I do not know how to do this sequentially, that is to say pulse enter and an action is executed, and when I press again another one is executed later. Without affecting the previous one. I access the key like that, but until now I've arrived.

	$('body').keyup(function(e) {
		if(e.which == 13){
		//ejecuto algo

		}
	});
    
asked by crismf 16.12.2017 в 18:04
source

2 answers

1

You could create a global counter and make a factory pattern an example would be the following

var cont = 0;

const Evento1 = function(){
 // ejecutas tu acción
 console.log("ejecutas tu acción 1")
}

const Evento2 = function(){
 // ejecutas tu acción
 console.log("ejecutas tu acción 2")
}

const funciones = [
  Evento1,
  Evento2
];

$('body').keyup(function(e) {
		if(e.which == 13){
		//ejecuto algo
    if(cont<funciones.length){
     funciones[cont]();
        cont++;
    }
        
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 16.12.2017 / 18:19
source
0

You could create a counter variable that increases its value with each enter and depending on the value execute an action:

var contador = 0;

$('body').keyup(function(e) {
  if(e.which == 13){
    switch(contador){
      case 0:
        console.log('Acción 1');
      break;

      case 1:
        console.log('Acción 2');
      break;

      case 2:
        console.log('Acción 3');
      break;

      case 3:
        console.log('Acción 4');
      break;
    }

    contador++;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 16.12.2017 в 18:19