使用.clone进行克隆时无效的事件(true)

Raj*_*amy 3 jquery

我只是想回答这个问题.实际上,op已经要求事件不会被克隆元素触发.在查看他的代码时,他使用了.clone()函数来完成他的任务,

所以我建议使用.clone(true).该文档说,如果我们通过的第一个参数为真在.clone()函数,然后将克隆副本将保留数据和他们的事件处理程序.但它的行为并非如此.我误解了什么......任何身体都可以引导我朝着正确的方向前进吗?

DEMO

代码取自小提琴,

$('button').on('click', function(){
  $(this).replaceWith('<p>'+ $(this).text() +'</p>');
  $(this).clone(true).appendTo('body');
});
Run Code Online (Sandbox Code Playgroud)

小智 7

如果颠倒.replaceWith().clone()它会工作:

$('button').on('click', function(){
  $(this).clone(true).appendTo('body');
  $(this).replaceWith('<p>'+ $(this).text() +'</p>');
});
Run Code Online (Sandbox Code Playgroud)

.replaceWith()会清除绑定到元素的所有事件(如讨论这里).当你打电话.clone()之后,没有事件可以保留.

我的猜测是,.clone()甚至在调用之前保留基本html(比如在内部变量中)并.clone(true)检索该值然后绑定事件.