This is a rather strange issue with jquery. I am loading a div

<div id="container">

on page load. Each record is tabular data with a 'delete' ajax function associated with it. When the page loads and clicking the 'delete' link, the ajax call fires off just fine. However, once the event is fired, the data is returned from the ajax call, and the div is populated with data (but the page does not refresh or reload) When I click the link again, the ajax script will not fire. Here is my code:

$(document).ready(function() {
    $("button.done").button({
    }).click(function() {
        var BatchID = $("input#BatchID").val();
        var Amount = $("input#Amount").val();
        var Name = $("input#CheckName").val();
        var Check_Number = $("input#Check_Number").val();
        var Company = $("select#Company").val();
        var Department = $("select#Department").val();
        $.ajax({
            type: 'GET',
            url: '/app/usagCheckEntryWS.html',
            data: {
                "BatchID" : BatchID,
                "Amount" : Amount,
                "Name" : Name,
                "Check_Number" : Check_Number,
                "Company" : Company,
                "Department" : Department
            },
            success: function (data) {
                    var ang = '';
                    var obj = $.parseJSON(data);
                    $.each(obj, function() {
                       ang += '<table><tr><td width="45">' + this["RefID"] + '</td><td width="140">' + this["Name"] + '</td><td width="95">' + this["CheckNumber"] + '</td><td align="right" width="70">$' + this["Amount"] + '</td><td width="220" style="padding-left: 15px;">' + this["Description"] + '</td><td><div class="delete" rel="' + this["RefID"] + '"><span>Delete</span></div></td></tr></table>';
                    });
                    $('#container').html(ang);
                    $("input#Amount").val('');
                    $("input#CheckName").val('');
                    $("input#Check_Number").val('');
                    $("select#Company").val('MMS');
                    $("th#dept").hide();
                    $('input#CheckName').focus();
            }
        });
    });
});

推荐答案

当您移除一个元素,然后(通过javascript)替换它时,它将丢失在页面加载时添加到它的所有事件绑定.

(这也适用于页面加载后添加到页面的内容-即Ajax加载的内容)

对此有几种可能的解决方案.

1) Encapsulate your "binding" code and call it both on page load and immediately after the element in question gets added back to the page. For example:

$(document).ready(function(){
    // bind event handlers when the page loads.
    bindButtonClick();
});

function bindButtonClick(){
    $('.myClickableElement').click(function(){
        ... event handler code ...
    });
}

function updateContent(){
    $.ajax({
        url : '/ajax-endpoint.php',
        data : {'onMyWay' : 'toServer'},
        dataType : 'html',
        type : 'post',
        success : function(responseHtml){
            // .myClickableElement is replaced with new (unbound) html element(s)
            $('#container').html(responseHtml);

            // re-bind event handlers to '.myClickableElement'
            bindButtonClick();  
        }
    });
}

2) The more elegant way to handle this: use jQuery's .on() method. With it, you are able to bind event handlers to elements other than the event target - i.e. an element that never gets removed from the page.

$(document).ready(function(){
    $('body').on('click','.myClickableElement',function(){
        ... event handler code ....
    });
});

Some further explanation:

The .on() method uses event delegation to tell a parent element to retain your event handler code (3rd argument), and fire it when the event target (2nd argument) has a certain type of event (1st argument) performed on it.

If you are using a version of jQuery prior to 1.7 use the now deprecated delegate method which essentially does the same thing.

另外,值得注意的是,由于事件在dom树中"冒泡"的方式,事件目标(on()方法的第二个参数)必须是委托元素(jQuery对象的 Select 器)的后代.例如,the following would NOT work

<div id="container-1">
    <div>
        <div id="another-div">
            Some Stuff
        </div>
    </div>
</div>

<div id="container-2">
    <a id="click-me">Event Target!!!</a>
</div>

<script type="text/javascript">
    $('#container-1').on('click','#click-me',function(){
        ... event handler code ....
        // This will never execute, should've used '#container-2', or 'body', or 'document' instead of '#container-1'
    });
</script>

bodydocument个元素通常是安全的 Select ,因为页面上的每个元素通常都是后代.

Jquery相关问答推荐

将div中的下一个2个标题分组

多个 AJAX 调用;获取所有失败的呼叫

在 Mastodon 中将 jQuery 添加到 Rails 6

如果您的 Select 器对象无效,为什么 jQuery 不会炸弹?

在 Javascript 中启用和禁用 Div 及其元素

使用 jQuery Validate 确认密码

Jquery .on('scroll')在滚动时不触发事件

确定 JavaScript 值是否为整数?

在不使用提交按钮的情况下触发标准 HTML5 验证(表单)?

动画元素变换旋转

jQuery Force 为 iframe 设置 src 属性

如何将数组传递给 jQuery .data() 属性

好处和.在本地托管 jQuery 的trap

如何让 twitter bootstrap 子菜单在左侧打开?

jQuery确定匹配的类是否具有给定的ID

在未实现接口 FormData 的对象上调用附加

D3 和​​ jQuery 有什么区别?

我应该在addClass之前使用hasClass吗?

JS - 从base64代码中获取图片的宽高

为什么我应该创建异步 WebAPI 操作而不是同步操作?