JQuery 单击函数在 ajax 调用后不工作?

JQuery click 函数在这里工作得很好

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


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

但是如果我用 ajax 设置一些 <a>$('.deletelanguage').click就不工作了。

比如说

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


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

现在,最后一个 <a>$('.deletelanguage').click不工作了。

Jsfiddle 示例: http://jsfiddle.net/suhailvs/wjqjq/

注意: CSS 在这里工作得很好。

我想让这些新添加的 <a>与 jQuery 单击一起工作。

183446 次浏览
$('body').delegate('.deletelanguage','click',function(){
alert("success");
});

or

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

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

Since the class is added dynamically, you need to use event delegation to register the event handler like:

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

This will attach your event to any anchors within the #LangTable element, reducing the scope of having to check the whole document element tree and increasing efficiency.

FIDDLE DEMO

Here's the FIDDLE

Same code as yours but it will work on dynamically created elements.

$(document).on('click', '.deletelanguage', function () {
alert("success");
$('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});

The click event doesn't exist at that point where the event is defined. You can use live or delegate the event.

$('.deletelanguage').live('click',function(){
alert("success");
$('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});

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

I tested a simple solution that works for me! My javascript was in a js separate file. What I did is that I placed the javascript for the new element into the html that was loaded with ajax, and it works fine for me! This is for those having big files of javascript!!