+ 1
Can't create element that replicate itself and give elements that themselves replicate
Hello I have this code: <p>click me to replicate</p> $(function (){ $("p").on("click", function(){ $("p:first").clone().appendTo("body"); } }); the problem is: only one is replicable.
7 ответов
+ 11
Okay, after ten minutes... i made an acceptable solution with a self-invoking function, i want to pointed out that i have no idea about native jQuery's methods and selectors, so... might be possible found an easier solution.
This is the script i used:
$(document).ready(function(){
(function generator(){
$("p").last().click(function(){
$(this).clone().appendTo("body");
generator();
})
})();
})
+ 8
Pure JS
------------------------------------------------------
<p>click me to replicate</p>
<script>
onload=function(){ document.getElementsByTagName("p")[0].addEventListener("click", function(){
var p = document.createElement("p");
p.innerHTML = "click me to replicate";
document.body.appendChild(p);
})
}
</script>
------------------------------------------------------
jQuery
------------------------------------------------------
<p>click me to replicate</p>
<script>
$(document).ready(function(){
$("p").click(function(){
$("p:first").clone().appendTo("body");
})
})
</script>
------------------------------------------------------
+ 4
@Maz wrote: << i made an acceptable solution with a self-invoking function, i want to pointed out that i have no idea about native jQuery's methods and selectors, so... might be possible found an easier solution. >>
Not a lot of skill and practice in JQuery, but I suggest this solution easiest to read at least... and avoiding self -invoking function, as it can be easier for non expert ;)
@Hacen Med wrote: << do you have an idea why the first approach didn't work? >>
Answer is mainly in explanation of the second approach, more readable in mine, after knowing that JS DOM API (wich is used by JQuery) clone() method doesn't duplicate event listener, even if they are available as attribut for the element ^^
$(document).ready(function(){
/*
need to have a reference to the event handler function, for set event listener with this reference at each clone, to avoid duplicate function definition
parameter 'e' is the event object automatically sent to an event handler
*/
function dup(e) {
// clone and append element throwing event to body
$(e.target).clone().appendTo("body");
// the appended element is necessarly the last:
// we select it, and set it our event handler
$("p:last").click(dup);
}
// we set the event handler to the initial existing <p>s elements
$("p").click(dup);
})
+ 1
thanks for your time.
this worked fine for me.
0
thank you very much
0
the same problem: only the first replicate itself, those generated doesn't
0
do you have an idea why the first approach didn't work?