Reputation: 1877
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
Upvotes: 0
Views: 368
Reputation: 66693
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/
Upvotes: 2
Reputation: 579
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!');
}
});
});
Upvotes: 0