-3

For example : When click on the aaa button, 'bbb' button is inserted but later when click on the bbb button i dont have allert. Why ?

<button id="aaaa">aaaa</button>
<div id="abc"></div>

<script>
   $("#aaaa").click(function() {
        $("#abc").html('<button id="bbb">bbb</button>');

    });

    $("#bbb").click(function() {
        alert("sasasa");
    });
 </script>
  • Come oooon, super classic question, has already been asked and answered countless times http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Jeremy Thille May 06 '15 at 14:40

2 Answers2

2

Basically your $("#bbb") returns no matches, so does not register the click event at all. That element only exists later.

As the item is added dynamically, you need to use a delegated event handler, attached to a non-changing ancestor of the element:

e.g.

$(document).on('click', "#bbb", function() {
    alert("sasasa");
});

This version of on applies the jQuery selector at event time, so the element does not need to exist until event time (rather than when the event was registered).

document is the default if nothing else is closer/convenient. Do not use body as it has a bug (to do with styling). In your example you probably want to attach to '#abc'.

e.g.

$('#abc').on('click', "#bbb", function() {
    alert("sasasa");
});
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • In this case he can use the first parent element that is already in the DOM: so the div containing the new button – Lelio Faieta May 06 '15 at 14:41
  • @Lelio Faieta: Already advised and already added that in description. The speed difference is negligible anyway as it is at user-click speed. – iCollect.it Ltd May 06 '15 at 14:41
  • You are right about performance. IMHO i prefer not to use document when possible for code readibility (just my own opinion anyway) :) – Lelio Faieta May 06 '15 at 14:43
0

Use this code:

$("#abc").on(click,'#bbb',function() {
    alert("sasasa");
});

cause you need to use delegated events to use jquery on elements added to a DOM

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74