$('#test').click(function () {
$('body').append($('<button>').prop('id', 'demo').text('Click me'))
});
$('#demo').click(function () {
alert('Hello world!')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Append</button>
I've checked in Console log
, no error was found. I think something may be: Element with id demo
does not exist, so no message would throw when clicking on it.
Is there any way to set new element (created by jQuery syntax) detects the event (onclick)?
I don't want to use this way:
var btnClick = function () {
alert('Hello world!')
};
$('#test').click(function () {
$('body').append($('<button>').prop('id', 'demo')
.attr('onclick', 'btnClick()').text('Click me'))
});