Pregunta

Hi to everyone I'm kind of confused here. I'm replacing an element using replaceWith(); from jQuery and it works good. But after transformation the clickable element does not work anymore. Here is my code

¿Fue útil?

Solución

Thats because the event binding is lost when you replace the element. replaceWith() essentially removes the element and all its event bindings and then replaces it with a new element. It does not persist the event bindings.

Bind the click event using .on() instead.

$('.menu').on('click', 'a', function() {
   ...
});

Updated Fiddle: http://jsfiddle.net/RTPhR/1/

Otros consejos

http://jsfiddle.net/RTPhR/5/ Bind the event to the menu not to the LINKS.

$(document).ready(function() {
    $('.menu').on('click','a',function() {
        var $this = $(this),
            element = $this.attr('name');

        if (element == 'opt1') {
            alert('opcion 1');

        } else if (element == 'opt2') {
            alert('opcion 2');
            $this.replaceWith("<a href='#' name='cerrar'>VOLVER</a>");

        } else if (element == 'cerrar') {
            alert('close!');
        }
    });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top