Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
getting variable from loop to function

so I was working on discord bot dashboard and I am trying to make redirect buttons that goes to discord server user selects. So I am trying to make dynamic address like: http://localhost:3000/dash/discord/servers/${guildid}, but when I get the guild id and try to pass it on button.onclick function I just get 3 and not ex. 1,2,3. Everything is in a loop so I am little bit confused. Please help!

All of the code is in html file - script

Loop code:

document.addEventListener('DOMContentLoaded', function () {

     for (var i = 0; i < guildsLength; i++) {

        var button = document.createElement('button');
        button.type = 'button';
        button.innerHTML = Guildss[i] + " ID: " + IDs[i];
        button.className = 'btn-styled';
        button.id = 'b1';
        button.onclick = function (){

           location.href = `http://localhost:3000/dash/discord/servers/${IDs[i]}`

        }

        document.body.appendChild(button);

     }

  }, false);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're getting always the last i value because of javascript closures. When onclick method is called, it access i variable defined in its outer function, and at that moment i has the value that had when for loop finished.

You could use <a> tags and store the url in href attribute. This way you don't need any callbacks, and if you want, you can style the anchor as a button.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda