Problem with your implementation is that when you are attaching event like
var $edit = $('<p />', { class: 'edit', text: 'Edit' }).addClass('edit').appendTo(div);
$('.edit').click(function () {
alert('Hallo');
});
Edit element which you created just now is not added to DOM it is appeded to div only, which is not added to DOM. thus in short it doesn't exists in DOM, thus event is not binded with the button.
So to fix the issue instead of binding event to $('.edit')
you need to bind event with $edit
.
var $edit = $('<p />', { class: 'edit', text: 'Edit' }).appendTo(div);
$edit.click(function () {
alert('Hallo');
});
DEMO
However I would recommend you to use Event Delegation as
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
Code
function addComment(name1) {
}
$('#divComments').on('click', '.edit', function () {
alert('Hallo');
});
DEMO with event delegation