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

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