jQuery click function doesn't work after ajax call? [duplicate]

The jQuery click function works fine here

<div id="LangTable"><a class="deletelanguage">delete</a></div>    

$('.deletelanguage').click(function(){
    alert("success");
});

but if I set some <a> by ajax, $('.deletelanguage').click doesn't work.

for example

function CreateRow(jdata) { 
    $('#LangTable').append('<a class="deletelanguage">delete</a>');
}

$.ajax({        
    url: "/jobseeker/profile/",
    success: CreateRow
});

Now the $('.deletelanguage').click for the last <a> is not working.

jsfiddle example :http://jsfiddle.net/suhailvs/wjqjq/

Note: the CSS works fine here.

I want to make these newly appended <a> working with jQuery click.


Solution 1:

The problem is that .click only works for elements already on the page. You have to use something like on if you are wiring up future elements

$("#LangTable").on("click",".deletelanguage", function(){
  alert("success");
});

Solution 2:

When you use $('.deletelanguage').click() to register an event handler it adds the handler to only those elements which exists in the dom when the code was executed

you need to use delegation based event handlers here

$(document).on('click', '.deletelanguage', function(){
    alert("success");
});