【问题标题】:jquery bind functions and triggers after ajax callajax调用后jquery绑定函数和触发器
【发布时间】:2011-10-14 08:06:28
【问题描述】:
function bindALLFunctions() {
  ..all triggers functions related go here
};


$.ajax({
        type: 'POST',
        url: myURL,
        data: { thisParamIdNo: thisIdNo },
        success:    function(data){
                        $(".incContainer").html(data);
                        bindALLFunctions();
        },
        dataType: 'html'
});

我是 ajax 和 JQuery 的新手。 我的 js-jquery 代码中有上面的 ajax 调用。 bindALLFunctions(); 用于在ajax调用后重新调用所有的触发器和函数。它按预期工作得很好。但是,我已经阅读了在初始操作完成后更好地加载某些内容的地方,因此我尝试添加/编辑以下两个但没有成功。 有什么想法吗?

1) ->    $(".incContainer").html(data, function(){
                                          bindALLFunctions(); 
                                        });

2) ->    $(".incContainer").html(data).bindALLFunctions();

【问题讨论】:

    标签: ajax function jquery eventtrigger


    【解决方案1】:

    也许你应该看看livedelegate 函数。您可以在应用开始时设置唯一的事件处理程序,所有加载的 ajax 代码都将自动绑定:

    $("table").delegate("td", "hover", function(){
        $(this).toggleClass("hover");
    });
    

    但如果您更喜欢使用 Jquery.ajax 调用,则必须执行以下操作:

    $.ajax({
            type: 'POST',
            url: myURL,
            data: { thisParamIdNo: thisIdNo },
            success:    function(data){
                            $(".incContainer").html(data);
                            bindALLFunctions(".incContainer");
            },
            dataType: 'html'
    });
    

    并将bindALLFunctions 转换为:

    function bindALLFunctions(selector) {
      ..all triggers functions related go here. Example:
      $('#foo', selector).bind('click', function() {
         alert('User clicked on "foo."');
      });
    };
    

    只会在给定选择器“下”绑定事件。

    【讨论】:

      【解决方案2】:

      您的初始代码很好。新版本不工作是因为html()函数没有回调函数。

      【讨论】:

        【解决方案3】:

        很难从你的问题中看出你想问什么,但我猜你想知道ready 函数。它可以让您在文档可用后调用您的 bindALLFunctions;只需执行$(document).ready(bindALLFunctions)$(document).ready(function() { bindALLFunctions(); })

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-02-03
          • 1970-01-01
          • 2023-04-09
          • 1970-01-01
          • 2012-11-25
          • 1970-01-01
          • 2018-08-29
          相关资源
          最近更新 更多