JQuery - the `on` event does not work after jQuery.replaceWith

I need a link: When it clicks, it will change the text, when the mouse leaves the text, it will return to the link.

HTML:

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

JS:

  $("a").on('click',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; }); 

The code only works for the first time. It seems that $("a").on("click",function(){}) does not work after replaceWith .

script: http://jsfiddle.net/uABC9/4/

I am using jQuery 1.10.1 and have tested both FF and Chrome. Please, help.

+8
jquery
source share
3 answers

Replace

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

by

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

so you can use delegated events. In doing so, your handler will be applied to future anchor elements that can be created, and this is what you need, given that you remove the anchor from the document when doing replaceWith

Demo

Read more about delegated events here (section "Direct and delegated events")

+11
source share

JQuery "on" works, but since it is a link, so when you click on it, it will link to another place.

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

Another reason may be that your code uses $ replace.replaceWith ($ lnk), becuase $ lnk is this. Thus, this means that he 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; 

});

+3
source share

When the document initially loads your a tag, click. But when the a tag is replaced with a new one, it no longer looks at the new tag.

I would recommend placing a div around your link and having jQuery to view all clicks on links in 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/

+1
source share

All Articles