简体   繁体   中英

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

Background: There are some values on my website which shall be editable via JavaScript and Ajax. The Ajax is working fine and I can edit values but after I saved the value I cannot edit it again without reloading the page.

I reduced the problem to this: The original element gets replaced with a HTML form. When the form is submitted the form itself is replaced by the new version of the display element, but the event listener is broken.

I put together some sample JS code ( JSfiddle ) which doesn't work as I 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 click ed text replaced with form (text element saved for simplicity)
  3. after button click text displayed again
  4. click on text works again as in step 2 (doesn't work now)

Why is the click event lost when using the text object again?

One option to make it work and not to rewrite the whole structure is to clone element with binded events:

text.click(function() {
    ...
    button.click(function() {
        $('#container').html(text.clone(true));
    });
    ...
})

$('#container').html(text.clone(true));

DEMO: http://jsfiddle.net/J8Sa7/2/

The .html() method (re)sets the innerHTML property to a text value . These strings have no event listeners - I think that's a bug in jQuery that .html() accepts anything than strings (and functions) ; in here your jQuery object seems to be even stringified.

To change the content to already existing DOM nodes, you will need to .empty() the container (or .remove() the text element) and .append() the button element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM