1

$('#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'))
});
Tân
  • 1
  • 13
  • 45
  • 86

1 Answers1

2

You should use event delegation on() :

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.

$('body').on('click', '#demo', function () {
     alert('Hello world!')
})

Hope this helps.

Zakaria Acharki
  • 63,488
  • 15
  • 64
  • 88