imkost
imkost

Reputation: 8163

jQuery create element and use it

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.

Upvotes: 0

Views: 2056

Answers (3)

Tats_innit
Tats_innit

Reputation: 34117

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');
        });
    });

Upvotes: 1

John Fisher
John Fisher

Reputation: 22727

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

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

Use on to bind to delegated events

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

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

Upvotes: 2

Related Questions