I am searching a way it can create jquery script when creating a new element.
Here is what I've done
<div id = "content">
content
</div>
<script>
$('#content').click(function(event) {
$('#content').append('<div id='+ Math.floor((Math.random() * 100) + 1) +'> 123 </div>');
});
// dynamically create click function?
$('#randomNumber').click(function(event) {
console.log("Random id");
});
</script>
You do not need to, since you can use .on() which applies to your current and future elements, like this:
$("#content").on("click", "div", function() {
console.log(this.id);
});
This essentially creates a click handler for all divs existent or not yet existent inside #content and the handler logs the id of this.
And your other handler of
$('#content').click(function(event) {
$('#content').append('<div id='+ Math.floor((Math.random() * 100) + 1) +'> 123 </div>');
});
creates such divs. Just make sure you do not duplicate ids, as that would lead to invalid HTML, which is punished when it comes to SEO scores.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With