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 answersi 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
Post a Comment