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

222
Visualizações
Cannot delete element created by jQuery

I use SignalR to push notifications. To be simple, I have created some elements using the following jQuery code:

<script>
    $(document).ready(function(){
        var connection = new signalR.HubConnectionBuilder().withUrl("/signalRServer").withAutomaticReconnect().build();
        connection.start();

        connection.on("ReceiveNotification", function(sender, workCenter, serviceType, notificationId){
            event.preventDefault();
            if($('#notifi-badge').length){
                var currentNotificationCount = parseInt($('#notifi-badge').text());
                $('#notifi-badge').text(currentNotificationCount + 1);
                $('.notification-items').prepend('<li><a class="dropdown-item notification-item" style="font-family: vazir !important" Id="'+ notificationId +'" href="#">New '+ serviceType +' for '+ workCenter +' sent.</a></li>');
            }else{
                $('#notifi-badge').text('1');
            }
        });
    });
</script> 

and I use the following code to detect those created items:

<script>
    $(document).ready(function(){
        $('.notification-item').on("click", function(){
        var selectedId = $(this).attr('Id');
        var notificationBadge = parseInt($('#notifi-badge').text());
        var formData = new FormData();
        alert(selectedId);

. . .

</script>

SignalR works fine and I can push notifications. When I click those created elements, I expect to alert but it does not.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Listen to the click event bubbling up from .notification-item to the nearest parent that is present at runtime: see event delegation using .on(). Your issue is due to .notification-item being dynamically added and is not available at runtime, so no click event handler is bound to it.

Without looking at your markup, is it not clear which is the nearest parent that is present at runtime: in this case I can suggest listening to the click event at the level of the document instead:

$(document).on('click', '.notification-item', function(){ ... })

If the element .notification-items (the parent that you're appending elements to) is indeed present at runtime, then you can do this:

$('.notification-items').on('click', '.notification-item', function(){ ... })
about 4 years ago · Juan Pablo Isaza Relatório

0

The click event is not binded to new attached items(.notification-item). To do so, you have to rebind events when each new items added:

  1. call the event binding function after new element prepended:

     <script>
         $(document).ready(function(){
             var connection = new signalR.HubConnectionBuilder().withUrl("/signalRServer").withAutomaticReconnect().build();
             connection.start();
             connection.on("ReceiveNotification", function(sender, workCenter, serviceType, notificationId){
                 event.preventDefault();
                 if($('#notifi-badge').length){
                     var currentNotificationCount = parseInt($('#notifi-badge').text());
                     $('#notifi-badge').text(currentNotificationCount + 1);
                     $('.notification-items').prepend('<li><a class="dropdown-item notification-item" style="font-family: vazir !important" Id="'+ notificationId +'" href="#">New '+ serviceType +' for '+ workCenter +' sent.</a></li>');
                     bindEvent();
                 }else{
                     $('#notifi-badge').text('1');
                 }
             });
         });
     </script> 
    
  2. and declare bindEvent function

     function bindEvent(){
         $('.notification-item').unbind("click").bind("click", function(){
             var selectedId = $(this).attr('Id');
             var notificationBadge = parseInt($('#notifi-badge').text());
             var formData = new FormData();
             formData.append("notificationId", selectedId);
             $.ajax({
                 type: "POST",
                 url: "/Page/DeleteNotification",
                 contentType: false,
                 processData: false,
                 data: formData,
                 success: function(response){
                     if(response.success){
                         $('#'+ selectedId +'').remove();
                         if(notificationBadge >= 1){
                             $('#notifi-badge').text(notificationBadge - 1);
                         }else{
                             $('.badge-notification').remove();
                         }
                     }else{
                         console.log("Error! Removing process failed.");
                     }
                 }
             });
         });
     }
    
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