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

115
Vistas
How to trigger click event of anchor tag via jQuery for dynamic data?

Trying to trigger click event of a tag with jQuery but the event is linked with data set by $.getJSON in a section.

Following is the code of HTML:

...

const page=1, dataList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `
        <div class="card col-xs-12 col-lg-4 my-2">
            <div class="card-body">
                   <figure> <img src=${element.image_url} class="img-fluid" alt=${element.name}></figure>
            <article class="ms-3">
                    <h5 class="card-title">${element.name}</h5>
                    <p class="card-text">${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}</p>
            </article>
<!--- This is what's suppose to give the event on click. --->
            <a href="javascript:void(0)"  id=${element.id}> <i class="fa fa-star-o usericon mt-3"></i></a>
            </div>
        </div>`
        temp += item;
    });
    return temp;
}

//this is what's not working
 $('.card a').click(function () {
    var usersid = $(this).attr("id");
    favouritesList.push(usersid);
    console.log(favouritesList);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section>

Please do guide if possible. Thanks.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Your code isn't working because your element isn't loaded with the page, so when jQuery runs $('.card a').click(function..., $('.card a') returns null, so the listener is not attached.

Add your listener to the document like so:

$(document).on("click", ".card a", function() { ... })

When the user clicks on the document, jQuery will check if $(".card a") is the target, even if added after the page was initially loaded, and will execute your function if it is.

about 4 years ago · Juan Pablo Isaza Denunciar

0

As @will already pointed out: it is a timing problem. In your code the click event was attached before the contents form your $.getJSON() arrives. By using a delegated event attachment you can solve the problem:

const page=1, dataList=[], favouritesList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        // console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `
        <div class="card col-xs-12 col-lg-4 my-2">
            <div class="card-body">
                   <figure> <img src=${element.image_url} class="img-fluid" alt=${element.name}></figure>
            <article class="ms-3">
                    <h5 class="card-title">${element.name}</h5>
                    <p class="card-text">${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}</p>
            </article>
<!--- This is what's suppose to give the event on click. --->
            <a href="javascript:void(0)"  id=${element.id}> <i class="fa fa-star-o usericon mt-3">click me</i></a>
            </div>
        </div>`
        temp += item;
    });
    return temp;
}

//this is now working:
 $('section').on("click",".card a",function () {
    favouritesList.push($(this).attr("id"));
    console.log(favouritesList);

});
.img-fluid {height:80px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section>

about 4 years ago · Juan Pablo Isaza Denunciar

0

ajaxComplete also solve your problem.

$(document).ajaxComplete(function () {
    $('.card a').click(function () {
        const favouritesList = [];
        let usersId = $(this).attr("id");
        favouritesList.push(usersId);
        console.log(favouritesList);
    })
})
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