Update value using For each event

Asked

Viewed 80 times

0

I have this code here:

var current  = 0;
var array1 = [1,2,3,4,5,6,8,9,10];

function aparecer(){
	//verifica se o current é maior do que o array
	if ( (array1.length - 1) < current ) {
		alert("oi");
		//isso deveria parar a função
		return false;
	}
	for (var i= current; i <= (current + 2); i++){
		const lugar = document.getElementById('local');

		const ul    = document.createElement('UL');
		const valor = document.createTextNode(array1[i])
		ul.appendChild(valor);

		lugar.appendChild(ul);

	} 
	current = i;
}

function desaparecer(){
 current = 0;
 document.getElementById('local').innerHTML= '';
  
}
<html>
  <button onClick='aparecer()'> Aparecer </button>
  
  <button onClick='desaparecer()'> Desaparecer </button>
  
  <div id='local'> </div>
  
</html>

And at each click I want to update the value 1,2,3, to 4,5,6, so successively and not add on screen again.

Someone can help me ?

1 answer

1


Before the for, empty the div with document.getElementById('local').innerHTML= '';:

var current  = 0;
var array1 = [1,2,3,4,5,6,8,9,10];

function aparecer(){
	//verifica se o current é maior do que o array
	if ( (array1.length - 1) < current ) {
		alert("oi");
		//isso deveria parar a função
		return false;
	}
       document.getElementById('local').innerHTML= '';
	for (var i= current; i <= (current + 2); i++){
		const lugar = document.getElementById('local');

		const ul    = document.createElement('UL');
		const valor = document.createTextNode(array1[i])
		ul.appendChild(valor);

		lugar.appendChild(ul);

	} 
	current = i;
}

function desaparecer(){
 current = 0;
 document.getElementById('local').innerHTML= '';
  
}
<button onClick='aparecer()'> Aparecer </button>
  
  <button onClick='desaparecer()'> Desaparecer </button>
  
  <div id='local'> </div>

  • Our brother, what a good kkkkk tip. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.