Jquery function click on PHP dynamic links

0

I'm trying to create a script for when the person clicks on Like it will enjoy the post, and when you click on Descortir, you will discard the post, of course, I managed to do it successfully, however I had to do this by putting the jquery script in the PHP, causing each result, a new script to be created, that would be very large. I wanted to leave only 1 code, how do I get the IDS there in the case of dynamic results?

I'll explain briefly, why it got a bit confusing, I want to instead of having to put this javascript in dynamic select, put only 1 code for everyone.

JQUERY

    $(document).ready(function(){
    // like and unlike click
    $("#like<?php echo $row['idd']; ?>, #unlike<?php echo $row['idd']; ?>").click(function(){

         var iconCarregando = $('<img src="loading.gif" width="70"> arregando. Por favor aguarde...');

                $('#statuslike<?php echo $row['idd']; ?>').html(iconCarregando);

            $.ajax({
        type: "GET",
        url: 'acoes.php?like=1&id=<?php echo $row['idd']; ?>',
        success: function(data){
      $(iconCarregando).remove();
    } });
    });
});

HTML

(the code is in half, why can not I put the whole code)

a href="javascript:void(0);" id="like'.$msg_id.'" title="Like" rel="Like"><i class="fa fa-hand-peace-o margin-r-5"></i> Aplaudir
    
asked by anonymous 30.10.2016 / 19:44

2 answers

1

You do not need to call the click event by the button ID. You can give a common class to all (ex. curtir ) and capture all the clicks there. After capturing you use $(this) to identify which button was clicked. If you do not have the ID information in another attribute, simply break the ID by the known part. Ex.:

$(document).ready(function(){
    // like and unlike click
    $(".curtir").click(function(){ // captura todos os cliques de curtir

         var iconCarregando = $('<img src="loading.gif" width="70"> arregando. Por favor aguarde...');

        var ID = $(this).attr('id').split('like')[1]; // pega o ID e retira a parte "like"

                $('#statuslike'+ID).html(iconCarregando);

            $.ajax({
        type: "GET",
        url: 'acoes.php?like=1&id='+ID,
        success: function(data){
      $(iconCarregando).remove();
    } });
    });
});
    
30.10.2016 / 20:25
0

If the element was created dynamically, use on of jQuery in the BODY element instead of direct click and of course insert this id in the element that contains the clickable class ex:

<div>
   <span id="id-do-botao-curtir" class="classe_clicavel">curtir</span>
</div>

$(body).on('click', '.classe_clicavel', function(){

    var id = $(this).attr('id');

    // ex de teste ou sua lógica
    alert(id);
});
    
30.10.2016 / 20:46