javascript - Recursively replaced element with editor (and back) breaks event listeners -


background: there values on website shall editable via javascript , ajax. ajax working fine , can edit values after saved value cannot edit again without reloading page.

i reduced problem this: original element gets replaced html form. when form submitted form replaced new version of display element, event listener broken.

i put sample js code (jsfiddle) doesn't work expect.

var text = $('<em/>').text('click me!');  text.click(function() {     var button = $('<input type="button" value="click me, too" />');      button.click(function() {         $('#container').html(text);     });      $('#container').html(button); })  $('#container').html(text); 

what shall happen:

  1. current value displayed
  2. after text clicked text replaced form (text element saved simplicity)
  3. after button click text displayed again
  4. click on text works again in step 2 (doesn't work now)

why click event lost when using text object again?

the .html() method (re)sets innerhtml property text value. these strings have no event listeners - think that's bug in jquery .html() accepts strings (and functions); in here jquery object seems stringified.

to change content existing dom nodes, need .empty() container (or .remove() text element) , .append() button element.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -