I have a statement adding a new div:
$('#dates').append('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>');
But I'd like to not only create element but also to assign on('click') action to it. Of course I could add generated id and then acces to created element by this id, but I feel that there is more beautiful solution.
Is it?
You don't need to add an id and then ask jQuery to parse a selector to find the element. You can directly do this :
$('#dates').append(
$('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>')
.click(function(){
// handle click
})
);
you can use jquery ON.. and also you can use class selector instead of id :) like $(".classname")
$('#dates').append('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>');
$('#dates').on('click','.'+classname, function(){
alert("on div click");
});
$('#dates').on('click','.month_selector', function(){
alert("on SPAN click");
});
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