jquery事件不会在ajax调用后触发 [英] Jquery Event won't fire after ajax call

查看:88
本文介绍了jquery事件不会在ajax调用后触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是jquery一个相当奇怪的问题。我正在加载一个div

 < div id =container> 

加载页面。每条记录都是带有与其关联的删除ajax函数的表格数据。当页面加载并点击'删除'链接时,ajax调用关闭就好了。
但是,一旦事件被触发,数据就会从ajax调用中返回,并且div中会填充数据(但页面不会刷新或重新加载)
当我再次单击链接时, ajax脚本不会触发。
这里是我的代码:

  $(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 ({
类型:'GET',
url:'/app/usagCheckEntryWS.html',
数据:{
BatchID:BatchID,
金额:金额,
姓名:姓名,
Check_Number:Check_Number,
公司:公司,
部门:部门
},
成功:函数(数据){
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 =rightwidth =70> $'+ this [Amount] +'< / td>< td width =220style =padding-left :15px;>'+ this [Description] +'< / td>< td>< div class =deleterel ='+ this [RefID] +'>< ; span>删除< / 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();
}
});
});
});


解决方案

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

有几种可能的解决方案。



)1)封装你的绑定代码,并在页面加载和相关元素被添加回页面后立即调用它。例如:

  $(document).ready(function(){
//页面绑定事件处理函数加载。
bindButtonClick();
});

函数bindButtonClick(){
$('。myClickableElement')。click(function(){
...事件处理程序代码...
}) ;


函数updateContent(){
$ .ajax({
url:'/ajax-endpoint.php',
data:{' onMyWay':'toServer'},
dataType:'html',
类型:'post',
成功:function(responseHtml){
// .myClickableElement被替换为new(unbound)html元素
$('#container')。html(responseHtml);

//将事件处理程序重新绑定到'.myClickableElement'
bindButtonClick();
}
});
}



<2> 处理此问题的更优雅方式 :使用 jQuery的.on()方法。使用它,您可以将事件处理程序绑定到除事件目标之外的其他元素 - 即永远不会从页面中移除的元素。

 <$ c $($'$')$($)$($)$($) .... 
});
});

一些进一步解释:

.on()方法使用 delegate 方法,它本质上是一样的。



另外,它是值得注意的是,由于事件通过dom树冒泡,事件目标(.on()方法的第二个参数)必须是委托元素(jQuery对象的选择器)的后代。例如,以下内容无效

 < div id =container-1> ; 
< div>
< div id =another-div>
一些东西
< / div>
< / div>
< / div>

< div id =container-2>
< a id =点击我>事件目标!!!< / a>
< / div>

< script type =text / javascript> $('#container-1')。on('click','#click-me',function(){
...事件处理程序代码....
} );
< / script>

body 或 document 元素通常是安全的选择,因为通常页面上的每个元素都是后代。


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

解决方案

When you remove an element and then replace it (via javascript), it loses any event bindings that were added to it on page load.

(This also applies to content added to the page after page load - i.e. ajax loaded content)

There are several possible solutions for this.

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.

Also, it is worth noting that because of the way events "bubble up" through the dom tree, the event target (2nd argument of .on() method) must be a descendant of the delegating element (jQuery object's selector). For example, 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 ....
    });
</script>

The body or document elements are usually safe choices since typically every element on the page is a descendant.

这篇关于jquery事件不会在ajax调用后触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆