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:
- current value displayed
- after text
clicked text replaced form (text element saved simplicity) - after button
clicktext displayed again clickon 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
Post a Comment