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

69
Visualizações
change text using arrays and button next

I am trying to use the elements on the array contenidoHistoria and actually created this function that responds to an event listener. But is only showing me the first element of the array and not the other elements as i press the button

var botonSiguiente = document.createElement('button')
botonSiguiente.setAttribute('id', 'siguiente')
botonSiguiente.innerText = 'Siguiente'
optionButtons = document.getElementById('option-buttons').appendChild(botonSiguiente)
document.getElementById('siguiente').addEventListener('click', siguiente, true)

//creating a 'sguiente' button event
var siguiente = function() {
var no_of_clicks = 0
//array that contains the infomration to pass everytime the button is clicked
var contenidoHistoria = ['texto 1', 'texto 2', 'texto 3', 'texto 4', 'texto 5']
var base = document.getElementById('base');
    base.innerHTML = `<p> ${contenidoHistoria[no_of_clicks]}</p>`
no_of_clicks == (contenidoHistoria.length - 1) ? no_of_clicks = 0 : no_of_clicks = no_of_clicks + 1;

}

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

0

The problem is that you define no_of_clicks every time the function siguiente is run, so it is reset to 0 on every click. If you take no_of_clicks out of the function, it will work as you intend. Also, it's a better practice to use let and const rather than using var as it prevents hoisting. I also took out contenidoHistoria outside of the function as well since it is also not something you need to create every time the function is run. :


let no_of_clicks = 0
//array that contains the infomration to pass everytime the button is clicked
const contenidoHistoria = ['texto 1', 'texto 2', 'texto 3', 'texto 4', 'texto 5']

const siguiente = function() {
  const base = document.getElementById('base');
  base.innerHTML = `<p> ${contenidoHistoria[no_of_clicks]}</p>`
  no_of_clicks == (contenidoHistoria.length - 1) ? no_of_clicks = 0 : no_of_clicks = no_of_clicks + 1;

}
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