Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

82
Visualizações
Bucle a través de colores

Estoy tratando de recorrer los colores y cambiar el texto de un h1 a uno de los colores en el ciclo

 <h1>Color Change </h1> <button id="btn">Click Here</button>
 const btn = document.querySelector('#btn')
 btn.addEventListener('click', () => { const h1 = document.querySelector('h1') const colors = ['red', 'yellow', 'brown', 'green', 'blue'] for (let i = 0; i < colors.length; i++) { h1.style.color = colors[i] } })

Solo está devolviendo el último color, mientras que quiero recorrer todos los colores. no estoy seguro de por qué

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

No desea recorrer todos los colores cuando hace clic en el botón. Debe mantener un recuento del índice de color actual, actualizar el color del texto y luego aumentar el recuento.

Mi técnica habitual para este tipo de problema es usar un cierre para limitar el número de variables globales que usamos.

 const btn = document.querySelector('#btn') const h1 = document.querySelector('h1'); btn.addEventListener('click', handleClick(), false); const colors = ['red', 'yellow', 'brown', 'green', 'blue']; // Closures work by returning a function from // the function that is called which maintains // a copy of its local lexical envionment (in // this case `count`). The function that is returned // is the function assigned to the button click listener // So, we initialise the count to zero function handleClick(count = 0) { // Return a function that maintains a copy // of `count` return function () { // If the count is less than the length // of the colors array change the text colour // and then increase the count if (count < colors.length) { h1.style.color = colors[count]; ++count; } } }
 <h1>Color Change </h1> <button id="btn">Click Here</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

Intente resumir el algoritmo en un lenguaje humano sencillo primero:

  • hay un elemento de título, un elemento de botón y un conjunto predefinido de colores;
  • inicialmente no se elige ningún color;
  • cada vez que se hace clic en el botón:
    • toma el siguiente color del conjunto;
    • aplique el siguiente color al elemento del título.

Ahora puedes convertir esto al código:

 // there is a title element, a button element, and a predefined set of colors const h1 = document.querySelector('h1') const btn = document.querySelector('#btn') const colors = ['red', 'yellow', 'brown', 'green', 'blue']; // no color is chosen initially let currentColorIndex = -1; // whenever the button is clicked ... btn.addEventListener('click', () => { // grab the next color from the set (if the current color is the last one, grab the first one then) const nextColorIndex = ++currentColorIndex % colors.length; // apply the next color to the title element h1.style.color = colors[nextColorIndex]; });
 <h1>Color Change </h1> <button id="btn">Click Here</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

Creo que la lógica que buscas es recorrer los colores en cada clic:

 const btn = document.querySelector('#btn') const h1 = document.querySelector('h1') const colors = ['red', 'yellow', 'brown', 'green', 'blue'] let i = 0; btn.addEventListener('click', () => { h1.style.color = colors[i]; // to change the color h1.innerHTML = colors[i]; // to change the text i = (i + 1) % colors.length; })
 <h1>Color Change </h1> <button id="btn">Click Here</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda