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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16598213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:26:09  来源:igfitidea点击:

How to bind Events on Ajax loaded Content?

javascriptjqueryhtmlajaxjquery-events

提问by confile

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

我有一个链接,myLink它应该将 AJAX 加载的内容插入到div我的 HTML 页面的(appendedContainer) 中。问题是click我与 jQuery 绑定的事件没有在插入到 appendedContainer 的新加载的内容上执行。该click事件绑定在未使用我的 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>

回答by dsgriffin

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 .mylinkinstead of data- http://jsfiddle.net/EFjzG/

这确实有效,这是一个示例,我在类中附加了一个锚点.mylink而不是data- http://jsfiddle.net/EFjzG/

回答by Kai

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-elementin the example below) that we know exists when the page loads. Here's how:

因为事件通过 DOM 向上传播,我们可以通过.parent-element在页面加载时我们知道存在的父元素(在下面的示例中)上创建一个委托事件来解决这个问题。就是这样:

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

Some more reading on the subject:

关于该主题的更多阅读:

回答by antoniputra

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 代码中

回答by Elnaz

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

回答by Real-Source

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

});

});

回答by ChristianG

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

例如,如果您的 ajax 响应包含 html 表单输入,那么这会很棒:

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

});

回答by ROMMEL

use jQuery.live() instead . Documentation here

改用 jQuery.live() 。文档在这里

e.g

例如

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

回答by Michael

For ASP.NET try this:

对于 ASP.NET,试试这个:

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

请在此处找到完整的讨论。