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

时间:2021-05-19 23:55:10

I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click event is bound on DOM elements that are not loaded with my AJAX function.

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

What do I have to change, such that the event will be bound?

我需要改变什么,才能使事件被绑定?

My HTML:

我的HTML:

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

My JavaScript:

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

The content to be loaded:

要加载的内容:

<div>some content</div>
<a class="mylink" href="otherurl">Link</a>

7 个解决方案

#1


131  

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/

这实际上是可行的,这里有一个例子,我添加了一个锚,它的类是。mylink而不是data - http://jsfiddle.net/EFjzG/

#2


13  

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!

如果在.on()之后追加内容,则需要在加载内容的父元素上创建委托事件。这是因为在调用.on()时(通常是在页面加载时)会绑定事件处理程序。如果在调用.on()时元素不存在,则不会将事件绑定到它!

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:

因为事件通过DOM传播,我们可以通过在父元素()上创建一个委托事件来解决这个问题。下例中的父元素),当页面加载时我们知道它的存在。方法如下:

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

Some more reading on the subject:

更多关于这个主题的阅读:

#3


4  

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

如果您的问题是“如何在ajax加载的内容上绑定事件”,您可以这样做:

$("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

因此,不需要将配置放置到每一个ajax代码中

#4


1  

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

在jQuery 1.7中,.live()方法被弃用。使用.on()附加事件处理程序。

Example -

的例子,

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

#5


0  

use jQuery.live() instead . Documentation here

使用jQuery.live()。文件在这里

e.g

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

#6


0  

For ASP.NET try this:

ASP。净试试这个:

<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.

请在这里找到完整的讨论。

#7


0  

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 :

对于那些仍在寻找解决方案的人来说,最好的方法是将事件绑定到文档本身,而不是将事件绑定到e的“on ready”。旅客:

$(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
        }
    });
});

});

});

#1


131  

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/

这实际上是可行的,这里有一个例子,我添加了一个锚,它的类是。mylink而不是data - http://jsfiddle.net/EFjzG/

#2


13  

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!

如果在.on()之后追加内容,则需要在加载内容的父元素上创建委托事件。这是因为在调用.on()时(通常是在页面加载时)会绑定事件处理程序。如果在调用.on()时元素不存在,则不会将事件绑定到它!

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:

因为事件通过DOM传播,我们可以通过在父元素()上创建一个委托事件来解决这个问题。下例中的父元素),当页面加载时我们知道它的存在。方法如下:

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

Some more reading on the subject:

更多关于这个主题的阅读:

#3


4  

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

如果您的问题是“如何在ajax加载的内容上绑定事件”,您可以这样做:

$("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

因此,不需要将配置放置到每一个ajax代码中

#4


1  

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

在jQuery 1.7中,.live()方法被弃用。使用.on()附加事件处理程序。

Example -

的例子,

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

#5


0  

use jQuery.live() instead . Documentation here

使用jQuery.live()。文件在这里

e.g

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

#6


0  

For ASP.NET try this:

ASP。净试试这个:

<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.

请在这里找到完整的讨论。

#7


0  

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 :

对于那些仍在寻找解决方案的人来说,最好的方法是将事件绑定到文档本身,而不是将事件绑定到e的“on ready”。旅客:

$(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
        }
    });
});

});

});