JQuery call element located inside append () with id

I am working on a dynamic web project using Jsf and jquery ..

$(function(){

 for(var i = 0 ; i < entitesFilleList.length ; i++){

    var nomEntite = entitesFilleList[i].nom;
    var $nomEntiteMere = entitesFilleList[i].entiteMere.nom;
    $nomEntiteMere = $nomEntiteMere.replace(/\s+/g, '');

    var contentMere = $('#'+$nomEntiteMere).html();                         
    var nomEntiteID = nomEntite.replace(/\s+/g, '');
    var lesCollaborateurs = $('.collaborateurs_of_'+nomEntiteID).text();

    var motherContent = $('#'+$nomEntiteMere).html();                               
    motherContent += '<li id="id_'+nomEntiteID+'"><span class="nomEntite">'+nomEntite+'</span><br/><ul id="'+nomEntiteID+'"></ul><a style="cursor:pointer" class="link" id="link_'+nomEntiteID+'">Equipe</a></li>';
    $('#'+$nomEntiteMere).html(motherContent);

  }

    $('a.link').click(function(){
        alert('I am clicked');
    })
})

the thing is, when I click the link, the warning does not appear, but when I add onclick = "alert ('I am clicked')" inside the tag, the warning appears.

Hope anyone can help
in advance thanks

+4
source share
1 answer

try this, it should work for you ...

$(function(){

     for(var i = 0 ; i &lt; entitesFilleList.length ; i++){

        var nomEntite = entitesFilleList[i].nom;
        var $nomEntiteMere = entitesFilleList[i].entiteMere.nom;
        $nomEntiteMere = $nomEntiteMere.replace(/\s+/g, '');

        var contentMere = $('#'+$nomEntiteMere).html();                         
        var nomEntiteID = nomEntite.replace(/\s+/g, '');
        var lesCollaborateurs = $('.collaborateurs_of_'+nomEntiteID).text();

        var motherContent = $('#'+$nomEntiteMere).html();                               
        motherContent += '<li id="id_'+nomEntiteID+'"><span class="nomEntite">'+nomEntite+'</span><br/><ul id="'+nomEntiteID+'"></ul><a style="cursor:pointer" class="link" id="link_'+nomEntiteID+' onClick = "TestFunction(link_'+nomEntiteID+')">' + Equipe + '</a></li>';
        $('#'+$nomEntiteMere).append(motherContent);
      }

    })
    function TestFunction(e){
        console.log("Link with id " + e + "is clicked.");
        }
0
source

Source: https://habr.com/ru/post/1671387/


All Articles