0

My html code is like this :

<button id="test-button-one">test button 1</button>
<div id="test"></div>

My javascript code is like this :

res = `<button id="test-button-two">test button 2</button`
$('#test-button-one').click(function(e){
        $('#test').html(res);
});
$('#test-button-two').click(function(e){
        alert('yeah')
});

Demo is like this :

https://jsfiddle.net/oscar11/qrdzf679/

If I click test button 1, it will display test button 2

Why when I click test button 2, it not display alert?

How can I solve it?

Success Man
  • 5,513
  • 23
  • 109
  • 205
  • 1
    https://jsfiddle.net/qrdzf679/1/ learn [Event Delegation](http://learn.jquery.com/events/event-delegation/) – Satpal Jun 09 '17 at 08:22
  • It is because when the above code runs, the element wasn't exist yet. You should use http://api.jquery.com/on/ – Chris Lam Jun 09 '17 at 08:23
  • What Satpal said: `$('#test').on('click', '#test-button-two', function(e) { alert('yeah') });` This works because the 3 parameter from of "on click" reacts to changes in the document. – Adder Jun 09 '17 at 08:24
  • 1
    You are adding "test-button-two" dynamically to the DOM. It was not loaded from the start. So you can use "$('body').on('click', 'test-button-two', function(){})". – Eswara Reddy Jun 09 '17 at 08:25
  • @Satpal, I need you help. Look at this : https://stackoverflow.com/questions/44486251/why-image-not-display-in-modal-bootstrap – Success Man Jun 11 '17 at 23:16

0 Answers0