在clone()之后,函数不起作用. jQuery的 [英] After clone(), function is not working. jQuery

查看:304
本文介绍了在clone()之后,函数不起作用. jQuery的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要当我单击按钮时它应该变成文本并克隆新按钮.执行克隆对象后.功能不起作用.这是我的代码

I wanted when i click the button it should turn into text and clone new button.After clone object executed. Function is not working. Here is my code

jQuery

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

HTML

<button>1</button>
<button>2</button>
<button>3</button>

演示

推荐答案

您需要事件委托:

事件委托允许我们将单个事件侦听器附加到父元素,该事件侦听器将为与选择器匹配的所有后代触发,无论这些后代现在存在还是将来添加.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('click','button', function(){
 $(this).replaceWith('<p>'+ $(this).text() +'</p>');
 $(this).clone().appendTo('body');
});

演示

Demo

这篇关于在clone()之后,函数不起作用. jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆