jQuery、AJAX 内容失去绑定(bind)

标签 jquery ajax binding

所以想象一下这个场景,我有一个列表,它有一些分页,当用户单击下一步时,链接被 jQuery 劫持,它使用 $.ajax 函数(我在下面提供了)去获取下一页内容并将它们显示在原始容器中。这包括分页链接,我们也希望它们更新。

第一个页面更改工作正常,但在这个阶段我们已经失去了链接元素和 jQuery 规则之间的绑定(bind):

$('#paging a').click(function(event) {
    event.preventDefault();
    getElementContents('#target_container','',$(this).attr('href'),false);
    // arguements are (target element, data (for $ajax), url (for $ajax), highlight)
});

我必须采取哪些选项来维护事件和函数之间的绑定(bind)?

作为引用,这是我的 $.ajax 的包装函数:

var ajax_count = 0;
function getElementContents(target,data,url,highlight) {
    if(url==null) {
        url='/';
    }
    if(data==null) {
        var data=new Array();
    }
    if(highlight==null || highlight==true) {
        highlight=true;
    } else {
        highlight=false;
    }

    $.ajax({
        url: url,
        data: data,
        beforeSend: function() {
            /* if this is the first ajax call, block the screen */
            if(++ajax_count==1) {
                $.blockUI({message:'Loading data, please wait'});
            } 
        },
        success: function(responseText) {
            /* we want to perform different methods of assignment depending on the element type */
            if($(target).is("input")) {
                $(target).val(responseText);
            } else {
                $(target).html(responseText);
            }
            /* fire change, fire highlight effect... only id highlight==true */
            if(highlight==true) {
                $(target).trigger("change").effect("highlight",{},2000)
            }
        },
        complete: function () {
            /* if all ajax requests have completed, unblock screen */
            if(--ajax_count==0) {
                $.unblockUI();
            }
        },
        cache: false,
        dataType: "html"
    });
}

谢谢! :-)

编辑

嗯,刚刚找到this question ...正在研究它:-)

最佳答案

尝试使用jquery.live:

$('#paging a').live('click', function(event) {
    event.preventDefault();
    getElementContents('#target_container','',$(this).attr('href'),false);
    // arguements are (target element, data (for $ajax), url (for $ajax), highlight)
});

如果使用 jQuery 1.9 或更高版本,.live 不再存在,因此您可以使用 .on 函数代替:

$(document).on('click', '#paging a', function (event) {
        event.preventDefault();
        getElementContents('#target_container','',$(this).attr('href'),false);
});

关于jQuery、AJAX 内容失去绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2773573/

相关文章:

javascript - Javascript 中最常见的计算能力浪费是什么?

jquery - 为什么 jGrowl 弹出窗口看起来不像预期的那样?

php - 创建一个表单以使用 MySQL 更新 JSON 数据

javascript - Ajax POST错误(400错误请求)

java - Spring MVC中init binder的目的是什么

WPF 数据网格 : CanContentScroll property causing odd behavior

jquery - 如何在jquery中为对话框设置cookie?

javascript - 我怎样才能确保每 2 种随机颜色被使用两次?

javascript - jQuery .done() .fail()

silverlight - 我在 MVVM 模型中使用 silverlight 两种方式绑定(bind)获得 Null 对象