jQuery: how to refer to new elements? -



jQuery: how to refer to new elements? -

this question has reply here:

event binding on dynamically created elements? 13 answers

i have code below. can guess, when press on "foobar", new element added. problem: when click on the new element nil happens, why? im using jquery 2.1.

<div> <span>foobar</span> </div> <script type="text/javascript"> $("span").on('click', function() { $(this).clone().appendto('div').addclass('new'); alert("click on first element"); }); $(".new").on('click', function() { alert("click on sec element"); }); </script>

two things

1)you have not added class correctly cloned element.

2)you need event delegation attach event dynamically added element.

$("span").on('click', function() { $(this).clone().addclass('new').appendto('div'); alert("click on first element"); }); $("div").on('click','.new', function() { alert("click on sec element"); });

working demo

jquery

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -