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

153
Visualizações
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 Respostas
Responde à pergunta

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 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