简体   繁体   English

通过ajax调用更新DOM后,单击事件上的jQuery丢失

[英]jQuery on click event is lost after DOM updated by ajax call

I have something working, but as I'm not a so used to code in JS, I don't know if it's the right way to do it. 我有工作的方法,但是由于我不太习惯用JS编写代码,所以我不知道这是否是正确的方法。

I have a simple: 我有一个简单的方法:

<div class="offers"></div>

And by calling myUrl , I retrieve ready to use HTML (some .offer div) that I then append to the .offers div. 然后通过调用myUrl ,检索准备使用的HTML(某些.offer div),然后append.offers div。 But I want to have a click event on these freshly appended .offer 但是我想对这些新添加的.offer进行click事件

$.ajax({
    'url': myUrl,
    success: function(data){
        offers.append(data);
        $('.offer').on('click', function(e) {
            e.preventDefault();
            $('.offers .offer').removeClass('selected');
            $(this).addClass('selected');
        });
    }
});

Thank you for your expertise ! 谢谢您的专业知识!

You can simply try that: 您可以简单地尝试:

$(document).on('click', '.offers .offer', function(e) {
    // Code here
});

Ideally, for performance purpose, replace document by the nearest ID on your DOM. 理想情况下,出于性能目的,请用DOM上最近的ID替换文档

UPDATE : After a comment from A. Wolff, I removed the "document.ready" not needed here. 更新 :在A. Wolff发表评论后,我删除了此处不需要的“ document.ready”。 (please read comment). (请阅读评论)。

Put the event handler outside the ajax: 将事件处理程序放在ajax外部:

$.ajax({
    'url': myUrl
}).done(function(data){
    var offers = $('.offers');
    offers.append(data);
});
$('.offers').on('click','.offer' function(e) {
   e.preventDefault();
   $('.offers').find('.offer').removeClass('selected');
   $(this).addClass('selected');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM