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

168
Vistas
How to "attach" JSON to a button so that the data can be used when clicked on it

Using js, I make a request from which I get a json response. I loop through the list and add an html div for every object in the list. Each div contains elements that show a bit of info coming from that object (e.g. title, id, info, etc.). A button is also added to those divs that when clicked should make a request. The url that the request should be made to is in the json object for that div. See:

#json object for div
{
    "name":"Test1",
    "id":15,
    "link":"http://example.com"
}

#js to make div; object above is stored in obj
table = document.getElementById('div-list');

entry = document.createElement("div");
title = document.createElement("div");
title.innerHTML = obj.name;
entry.appendChild(title);

button = document.createElement("button");
button.innerHTML = 'Click me';
button.addEventListener("click", function() {
    data = {
        'id': [[  obj.id  ]]
    }
    fetch([[ obj.link ]], {
        method: 'POST',
        body: JSON.stringify(data)
    })
});
entry.appendChild(button);

table.appendChild(entry);

You can see the [[ obj.id|obj.link ]]. That is where the info from the json needs to go. However, doing obj.id or obj.link doesn't work because the function is run when clicked so the variable obj doesn't exist anymore. So I basically need to store the json in the entry-element so that when the button is clicked it can get it's info from somewhere.

I hopy you understand what I mean. Is there some way to allow that button-click-function access to "it's data" in order for it to determine where to send it's request to with what id?

about 4 years ago · Santiago Trujillo
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