jQuery - `on` event doesn't work after jQuery.replaceWith

Replace

$("a").on('click',function(){

by

$(document).on('click','a',function(){

so you can use delegated events. Doing so, your handler will apply for future anchor elements that could be created and this is what you need taking into account that you're removing the anchor from document when executing replaceWith

DEMO

More details about delegated events here (check section "Direct and delegated events")


The jQuery "on" works, but because it is a link so when you click it will link to other place.

Here is one fiddle : http://jsfiddle.net/joydesigner/4f8Zr/1/

Another reason might be your code use $replace.replaceWith($lnk), becuase $lnk is this. So it means it will still use the same text and link.

Here is the code:

$("a").on('click',function(){
  var $lnk = $(this),
      $replace = $('<span>');

$replace.text($lnk.text());
// Link to Text
$lnk.replaceWith($replace);

// Text to Link
$replace.one('mouseout',function(e){
    $replace.replaceWith('<a href="#">test</a>');
});

e.preventDefault();
return false;

});


When the document originally loads its watching your a tag for a click. But when the a tag gets replaced with a new one its not longer watching the new tag.

I would reccomend putting a div around your link and having jQuery watch for all link clicks within the div. As shown in my example.

HTML

<div id="test">
   <a href="#">click me and change to text</a>
</div>

jQuery

$("#test").on('click','a',function(){
   var $lnk = $(this);
   var $replace = $('<span>');
   $replace.text($lnk.text());
   // Link to Text
   $lnk.replaceWith($replace);
   // Text to Link
   $replace.one('mouseout',function(){
      $replace.replaceWith($lnk);
   });
   return false;
});

http://jsfiddle.net/uABC9/8/

Tags:

Jquery