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

有帮助吗?

解决方案

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/

其他提示

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!');
        }
    });
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top