如何绑定 Ajax 加载的内容上的事件?

我有一个链接 myLink,它应该将加载 AJAX 的内容插入到 HTML 页面的 div(appenddContainer)中。问题是,我用 jQuery 绑定的 click事件没有在插入 appendedContainer 的新加载内容上执行。click事件绑定在没有用我的 AJAX 函数加载的 DOM 元素上。

我必须做些什么改变,才能使事件受到约束?

我的 HTML:

<a class="LoadFromAjax" href="someurl">Load Ajax</a>
<div class="appendedContainer"></div>

我的 JavaScript:

$(".LoadFromAjax").on("click", function(event) {
event.preventDefault();
var url = $(this).attr("href"),
appendedContainer = $(".appendedContainer");


$.ajax({
url: url,
type : 'get',
complete : function( qXHR, textStatus ) {
if (textStatus === 'success') {
var data = qXHR.responseText
appendedContainer.hide();
appendedContainer.append(data);
appendedContainer.fadeIn();
}
}
});


});


$(".mylink").on("click", function(event) { alert("new link clicked!");});

要载入的内容:

<div>some content</div>
<a class="mylink" href="otherurl">Link</a>
155553 次浏览

Use event delegation for dynamically created elements:

$(document).on("click", '.mylink', function(event) {
alert("new link clicked!");
});

This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/

use jQuery.live() instead . Documentation here

e.g

$("mylink").live("click", function(event) { alert("new link clicked!");});

For ASP.NET try this:

<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.

if your question is "how to bind events on ajax loaded content" you can do like this :

$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');


// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});

so you don't need to place your configuration to every you ajax code

If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!

Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:

$('.parent-element').on('click', '.mylink', function(){
alert ("new link clicked!");
})

Some more reading on the subject:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

Example -

$( document ).on( events, selector, data, handler );

For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready" For e.g :

$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'post',
url: url,
data: $(this).serialize(),
success: function (data) {
// DO WHAT YOU WANT WITH THE RESPONSE
}
});
});

});

If your ajax response are containing html form inputs for instance, than this would be great:

$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) {
if (this.value == 'Yes') {
// do something here
} else if (this.value == 'No') {
// do something else here.
} else {
console.log('The new input field from an ajax response has this value: '+ this.value);
}


});

Important step for Event binding on Ajax loading content...

01. First of all unbind or off the event on selector

$(".SELECTOR").off();

02. Add event listener on document level

$(document).on("EVENT", '.SELECTOR', function(event) {
console.log("Selector event occurred");
});

Here is my preferred method:

// bind button click to function after button is AJAX loaded
$('#my_button_id').bind('click', function() {
my_function(this);
});


function my_function () {
// do stuff here on click
}

I place this code right after the AJAX call is complete.

I would add one point that was NOT obvious to me as a JS newb - typically your events would be wired within document, e.g.:

$(function() {
$("#entcont_table tr td").click(function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
}

With event delegation however you'd want:

$(function() {
// other events
}


$("#entcont_table").on("click","tr td", function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});

If your event delegation is done within the document ready, you'll an error of the like:

cant assign guid on th not an boject