문제

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