简体   繁体   English

使用编辑器(和返回)递归替换元素会中断事件侦听器

[英]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. 背景:我的网站上有一些值可以通过JavaScript和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. Ajax工作正常,我可以编辑值,但在保存值后,我无法再次编辑它而无需重新加载页面。

I reduced the problem to this: The original element gets replaced with a HTML form. 我将问题简化为:原始元素被HTML表单替换。 When the form is submitted the form itself is replaced by the new version of the display element, but the event listener is broken. 提交表单时,表单本身将由新版本的display元素替换,但事件侦听器已损坏。

I put together some sample JS code ( JSfiddle ) which doesn't work as I expect. 我把一些示例JS代码( JSfiddle )放在一起,它不能像我期望的那样工作。

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) 在文本后click ed文本替换为窗体(为简单起见保存文本元素)
  3. after button click text displayed again 按钮后再次click显示的文本
  4. click on text works again as in step 2 (doesn't work now) click文本再次工作,如步骤2(现在不起作用)

Why is the click event lost when using the text object again? 为什么再次使用text对象时click事件会丢失?

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/ 演示: http //jsfiddle.net/J8Sa7/2/

The .html() method (re)sets the innerHTML property to a text value . .html()方法 (re)将innerHTML属性设置为文本值 These strings have no event listeners - I think that's a bug in jQuery that .html() accepts anything than strings (and functions) ; 这些字符串没有事件监听器 - 我认为jQuery中的一个错误是.html()接受的不是字符串(和函数) ; in here your jQuery object seems to be even stringified. 在这里,你的jQuery对象似乎甚至是字符串化的。

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. 要将内容更改为现有DOM节点,您需要.empty()容器(或.remove()文本元素)和.append()按钮元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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