doniyor
doniyor

Reputation: 37876

after jquery insert - element isnot seen

i have this problem:
i am inserting certain html thru jquery. and in that inserted html i have a class to which i have binded a function. this function isnot beeing called, i have the feeling, the inserted html isnot seen yet by js.

my inserting code.

$(function(){
  $('#einf').on('click', function(){
    $('<tr><td><a class="ame">delete</a></td></td></tr>').insertAfter('#append_tr');
  });
});

you can assume, inserting is working well. and this is my binded function:

$(function(){
  $('.ame').on('click', function(){
     alert('test');
  }); 
});

i tested with already existing element with the same class ame, it is working with that. thanks for help and guidance

Upvotes: 0

Views: 118

Answers (4)

Amit
Amit

Reputation: 1442

try .live() instead .on()

http://jsfiddle.net/ThobiasN/Pt3db/

  $(function(){ 
    $('#einf').on('click', function(){ alert ('some');
      $('<tr><td><a class="ame">delete</a></td></td></tr>').insertAfter('#append_tr');
    });
    $('.ame').live('click', function(){
       alert('test');
    }); 
  });

Upvotes: 1

Jai
Jai

Reputation: 74738

Try with event delegation: http://jsfiddle.net/xehu9/

$('#einf').on('click', '.ame', function(e){ //<-----pass it here.
    e.stopPropagation(); //<---------stop the event bubbling here.
    alert('test');
});

This happens because you are trying to implement the click on a elem which is not present in the dom when page gets ready.

from the docs:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Upvotes: 1

Solorzano Jose
Solorzano Jose

Reputation: 632

You cannot reference an element that was dinamically created, because it's not in the DOM when javascript runs, I suggest you use TEMPLATES instead of dinamic html content.

However, if you want to follow this approach, jquery allows concadinating element methods:

$(function(){
$('#einf').on('click', function(){
$('<tr><td><a class="ame">delete</a></td></td></tr>')
.insertAfter('#append_tr')
.on('click',function(){
 alert('test');
});
});
});

Upvotes: 0

Robert Fricke
Robert Fricke

Reputation: 3643

You have to run the click bind again on the added element. Maybe something like this will work:

$('<tr><td><a class="ame">delete</a></td></td></tr>').insertAfter('#append_tr').find('.ame').on('click', function(){
    alert('test');
});

Upvotes: 3

Related Questions