0

Here's a jsFiddle test --> http://jsfiddle.net/rTXkM/

I have a button that adds a table row to my table:

var x = "<tr><td><button class='del'> - </button></td></tr>";
$('#mytable').append(x);

I also have a jQuery function that operates according to class:

$('.del').click(function() {
   ......................
   ......................
   ......................
});

However, the 'del' class click function does not work on DOM created Elements... Can someone help?

jsFiddle --> http://jsfiddle.net/rTXkM/

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sanya
  • 1,270
  • 5
  • 21
  • 47
  • Event delegation is what you're looking for. – Musa Sep 04 '13 at 19:33
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Jason P Sep 04 '13 at 19:38

2 Answers2

4

You need to delegate like this $(document).on('click','.del',function() {

Demo here

Because your .del elements were not there when the listener was run (inside your .ready() function), the element did not get a event attached to it. So you need to delegate to something that was there before to be able to catch the click on that element.

You can read more at jQuery's documents: .on()

Sergio
  • 28,539
  • 11
  • 85
  • 132
2

Use

$(document).on("click", '.del', function() {
   alert('I work now');
}

and it will work. jQuery Documentation

Martin
  • 3,096
  • 1
  • 26
  • 46