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

294
Visualizações
Creating different instances of a function to be called later in javascript

Im trying to implement a dashboard in javascript, and am having some trouble with one of the components.

My code recieves a list of servers from an api, and I create and copy of a list item for each.

for (var i = 0; i < userData.servers.length; i++) {
      var server = userData.servers[i];
      var clone = serverElement.cloneNode(true);
      
      var serverImage = clone.getElementsByClassName("server-image")[0];
      var serverName = clone.getElementsByClassName("server-name")[0];
      var serverSelect = clone.getElementsByClassName("server-select")[0];
      
      serverName.innerText = server.name;
      serverImage.src = "https://cdn.discordapp.com/icons/" + server.id + "/" + server.icon + ".png?size=128";

      serverSelect.innerText = "Select";
      serverSelect.onclick = () => { setPremiumServer(server.id) };
      
      serverList.appendChild(clone);
}

However an issue arises with setting the onclick function of the button 'serverSelect'.

serverSelect.onclick = () => { setPremiumServer(server.id) };

When a button on one of the list items is pressed, I want it to call 'setPremiumServer' with the parameter being the ID corresponding to the server represented by the list item.

The way I attempted to do this was by creating an instance of a function, with the value set inside of it.

However, it appears this code isnt evaluated until the button is pressed, at which point it calls setPremiumServer() with the ID of the server that appears last in the list.

How would I fix this, and make it correctly call the function with the ID of the server represented by the list element?

about 4 years ago · Juan Pablo Isaza
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