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

223
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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