为什么我从jquery生成的按钮没有事件? [英] Why my generated button from jquery doesn't have an event?

查看:70
本文介绍了为什么我从jquery生成的按钮没有事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我从jquery生成的按钮没有事件?

Why my generated button from jquery doesn't have an event?

<input type='button' value='Populate' id='pop'/>
<input type='button' value='Click' id='btn'/>

$('#pop').on('click', function(){
   var clone = $('input[id*=btn]').clone();
   $(this).after(clone);
});

$('#btn').on('click', function(){
   alert('clicked'); 
});

小提琴

推荐答案

您将在应用事件侦听器之后创建克隆按钮 .当您克隆()仅元素 时,将克隆DOM结构,而不会克隆事件.

You are creating the cloned button after you have applied event listeners. When you clone() an element ONLY the DOM structure is cloned, the events are not.

或者是用户事件委托,或者只是将true传递给clone()使其也可以克隆事件的功能(根据规范)

Either user Event Delegation or simply pass true to the clone() function to have it clone the events also (as per the spec)

$('#pop').on('click', function(){
   var clone = $('input[id*=btn]').clone(true); // < pass true here
   $(this).after(clone);
});

演示: http://jsfiddle.net/rvhhv8sf/3/

P.S. ID必须是唯一的;)

P.S. Id's must be unique ;)

这篇关于为什么我从jquery生成的按钮没有事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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