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

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

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 Relatório

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 Relatório

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