2

I have html, I need to append a row in a table dynamically, also I need to catch the click event in the append div class. How to achieve this any idea?

JavaScript:

$(document).ready(function() {

    $("#click").click(function() {
        $('table').prepend('<tr> <td>something3</td> <td> <a><div class="s"> s </a> </td></tr>');
    });


    $(".s").click(function() {
        alert("Ok");
    });

});

HTML:

<input type="button" id="click" value="click"/>

<table width='100%'>
    <tr><td>something</td><td>else here</td></tr>
    <tr><td>something2</td><td>else here2</td></tr>
    <tr><td>something3</td><td>else here3</td></tr>
</table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
venkat
  • 131
  • 2
  • 12

1 Answers1

5

See the live() method, it allows you to bind an event for all current, and future elements in the DOM that match the given selector.

 $(".s").live('click', function(){
    alert("Ok");

 });

jQuery docs say:

Attach a handler to the event for all elements which match the current selector, now and in the future


Note that this answer was written in October 2011, when jQuery 1.6.4 was king. live() was deprecated in 1.7 in favour of using on(). The equivalent syntax is now;

 $(document).on("click", ".s", function(){
    alert("Ok");
 });
Matt
  • 74,352
  • 26
  • 153
  • 180
  • Most jQuery experts recommend the .delegate function rather than the .live function: http://test.kingdesk.com/jquery/bind_live_delegate.php – Steve Wellens Oct 14 '11 at 13:26
  • Correct, I would add however that delegate is considered to be faster and more flexible (chain-able) to live. http://api.jquery.com/delegate/ – rdjs Oct 14 '11 at 13:29
  • update to my previous comment, on() was introduced since this answer was posted http://stackoverflow.com/questions/8359085/delegate-vs-on – rdjs Sep 07 '12 at 12:53