最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to trigger event on clonedinserted element in DOM? - Stack Overflow

programmeradmin1浏览0评论

I am not able to trigger event on element I clone/insert to the DOM.

Check the fiddle here.

HTML:

<div class="A">[THIS IS DIV A]</div>
<div class="B">CLICK TO CLONE DIV A</div>

jQuery:

$('.A').on("click",null,function() {    
    alert('DIV A CLICK');           
});

$('.B').on("click",null,function() {        
    $('.A').clone().insertAfter('.A');          
});

If I click on a cloned DIV A, nothing happens.

How can I trigger event on cloned element?

I am not able to trigger event on element I clone/insert to the DOM.

Check the fiddle here.

HTML:

<div class="A">[THIS IS DIV A]</div>
<div class="B">CLICK TO CLONE DIV A</div>

jQuery:

$('.A').on("click",null,function() {    
    alert('DIV A CLICK');           
});

$('.B').on("click",null,function() {        
    $('.A').clone().insertAfter('.A');          
});

If I click on a cloned DIV A, nothing happens.

How can I trigger event on cloned element?

Share Improve this question edited Jul 17, 2013 at 14:21 j08691 208k32 gold badges269 silver badges280 bronze badges asked May 8, 2013 at 23:54 Peter LurPeter Lur 7582 gold badges13 silver badges27 bronze badges 2
  • 1 Possible dup: stackoverflow./questions/9549643/… – David Tansey Commented May 8, 2013 at 23:58
  • 1 That's officialy a dup. Ill delete it. I flagged it. – Peter Lur Commented May 9, 2013 at 0:04
Add a ment  | 

1 Answer 1

Reset to default 8

There are two solutions I propose.

Firstly, and the better option in this case, would be to add the true argument to clone(), for example in this case it would be:

$('.A').clone(true).insertAfter('.A');

As first argument of clone() represents:

"A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false." - jQuery API section for clone().

This means all bound events will be kept on each cloned element.

jsFiddle here.


The second option, probably not the way to go for this example, would be to use on()'s event delegation feature:

"Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time." - jQuery API section for on().

In this case:

$(document).on("click", ".A", function() { ...

Now, every new element with the class .A will be have this click event attached to it, even cloned elements.

jsFiddle here.

发布评论

评论列表(0)

  1. 暂无评论