0

For example, I have something like:

<div id="buttons">
    <button class="button">Click</button>
</div>

<script>
    $(document).ready(function() {
        $('.button').click(function() {
            $('#buttons').append('<button class="button">Click</button>');
        });
    });
</script>

When I press "Click" button, the script will create a new button with the same class "button". When I press this new button -- nothing happens.

I understand why, but I don't know how to avoid this. I want my script "see" just created button.

imkost
  • 8,033
  • 7
  • 29
  • 47

3 Answers3

2

Use on to bind to delegated events

$("#buttons").on("click", ".button", function () {
   $('#buttons').append('<button class="button">Click</button>');    
});

Example: http://jsfiddle.net/66H8W/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
1

Hiya demo : http://jsfiddle.net/vcrF3/ **or http://jsfiddle.net/vcrF3/1/

http://api.jquery.com/on/ quote

events-mapA map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).

Jquery code

   $.fn.ready(function() {
       $('div').on("click", ".button",  function() {
           $('#buttons').append('<button class="button">Click</button>');
          // alert('append button is clicked');
        });
    });
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
0

Read http://api.jquery.com/on/, paying particular attention to the "direct and delegated events" section.

John Fisher
  • 22,355
  • 2
  • 39
  • 64