jQuery ajax post 后执行 document.ready

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5610321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:28:25  来源:igfitidea点击:

Execute document.ready after ajax post

jqueryajaxruby-on-rails-3postdocument-ready

提问by Jason Yost

I have a custom.js file in which I have several elements that have click and other methods bound to them. The entire file is encapsulated in document.ready() and everything works. However when I do an AJAX post obviously document.ready() is never fired again for the current page. Is there anyway I can get document.ready() to fire again or do I need to have everything in named functions call them form my create.js.erb?

我有一个 custom.js 文件,其中有几个元素绑定了 click 和其他方法。整个文件被封装在 document.ready() 中,一切正常。但是,当我执行 AJAX 帖子时,显然 document.ready() 永远不会为当前页面再次触发。无论如何我可以让 document.ready() 再次触发,或者我是否需要让命名函数中的所有内容都从我的 create.js.erb 中调用它们?

回答by Ben

You could always just put everything in one function (named loadfunction or something) and call that function when the document loads, and again when the ajax is loaded. Though it is a hacked together solution, it should work well enough.

您总是可以将所有内容放在一个函数中(名为 loadfunction 或其他函数),并在加载文档时调用该函数,并在加载 ajax 时再次调用该函数。尽管它是一个组合在一起的解决方案,但它应该可以很好地工作。

So then take everything between $(document).onready(function () {and its end bracket }And put it in function OnloadFunction () {ending with }. Then put $document.onready(OnloadFunction);

因此,然后取其$(document).onready(function () {结束括号之间的所有内容并将其}放在function OnloadFunction () {}. 然后放$document.onready(OnloadFunction);

Example: You have

例子:你有

$(document).ready(function () {alert("test");});

It would turn into:

它会变成:

function OnloadFunction ()
{
    alert("test");
}
$(document).ready(OnloadFunction);

Then you can call OnloadFunctionwhenever you want to.

然后你可以随时打电话OnloadFunction

回答by Ken Mc

Combining Ben and fotanus' answers I created the following pattern:

结合 Ben 和 fotanus 的回答,我创建了以下模式:

$(document).ready(function () {
    AjaxInit()
});

$(document).ajaxComplete(function () {
    AjaxInit()
});

function AjaxInit() {
    alert("test");
}

回答by fotanus

There is a event that triggers after every ajax call. It is called ajaxComplete.

每次ajax调用后都会触发一个事件。它被称为ajaxComplete

$( document ).ajaxComplete(function() {
    $( ".log" ).text( "Triggered ajaxComplete handler." );
});

回答by Már ?rlygsson

I've successfully used a pattern like the following:

我已经成功地使用了如下模式:

First off we must define a .query() plugin.

首先,我们必须定义一个 .query() 插件。

// jQuery.fn.query() emulates the behavior of .querySelectorAll() 
// by allowing a full/complex selector to be matched against
//a small slice of the dom. 
$.fn.query = function ( selector ) {
    var scopeElms = this,
        scopeIsDoc = scopeElms.length === 1  &&  scopeElms.is('html') ,
        // check for obviously simple selectors.... (needs more elegance)
        isComplexSelector = /\s/.test( selector.replace(/\s*([|~*$\^!]?=|,)\s*/g, '') ),
        elms;
    if ( scopeIsDoc  ||  isComplexSelector )
    {
      elms = $(selector);
      if ( scopeElms[0] )
      {
        elms = elms.filter(function(){
            var i = scopeElms.length;
            while (i--) {
              if ( scopeElms[i] === this || $.contains(scopeElms[i], this) )
              {
                return true;
              }
            }
            return false;
          });
      }
    }
    else
    {
      elms =  scopeElms.filter( selector )
                  .add( scopeElms.find(selector) );
    }
    return $(elms);
  };

We then write our init function and bind it to the "ready" event, and also to our custom "domupdated" event. Within the init function we use .query()to find elements from either the whole document or just the updated fragment...

然后我们编写我们的 init 函数并将它绑定到“ready”事件,以及我们自定义的“domupdated”事件。在 init 函数中,我们用于.query()从整个文档或仅更新的片段中查找元素...

// Here we define our DOM initializations
$(document).bind('ready domupdated', function (e, updatedFragment) {
    var root = $( updatedFragment || 'html' );

    // Begin imaginary initialization routines
    root.query('form').validate();
    root.query('.sidebar .searchform input#search').autocomplete();
    // etc...

  });

Then whenever we inject blocks of new elements into the DOM (like when an Ajax request has finished) we then trigger the domupdatedevent and pass the updated DOM fragment as a parameter - like so:

然后,每当我们将新元素块注入 DOM 时(例如当 Ajax 请求完成时),我们就会触发domupdated事件并将更新的 DOM 片段作为参数传递 - 如下所示:

...
var ajaxedDom = $(xhr.resultText).find('#message');
ajaxedDom.appendTo( '#modal' );

$(document).trigger('domupdated', [ajaxedDom]);

For me, this set up takes all the pain out of initing the DOM. It allows me to maintain a single set of init routines, and focus on the fun things.

对我来说,这个设置消除了初始化 DOM 的所有痛苦。它允许我维护一组初始化例程,并专注于有趣的事情。

回答by byork2005

Minor twist on Ken Mc's answer. For whatever reason my ajaxComplete would not fire unless it was nested within a document.ready. Nesting it inside and still calling out worked for me.

肯麦克的回答略有不同。无论出于何种原因,我的 ajaxComplete 都不会触发,除非它嵌套在 document.ready 中。将它嵌套在里面并仍然呼叫对我有用。

$(document).ready(function () {
    AjaxInit();

    $(document).ajaxComplete(function () {
      AjaxInit()
    });
});

function AjaxInit() {
    alert("test");
}

回答by Brudka

I've used some trick. ;) All code is inside loaded part of file (ajax). I don't use any 'success', 'done' or etc. extended functionall of jquery ajax load.

我使用了一些技巧。;) 所有代码都在文件(ajax)的加载部分内。我不使用任何“成功”、“完成”或其他 jquery ajax 加载的扩展功能。

First we must build any function. For Example: _autostart();

首先,我们必须构建任何函数。例如:_autostart();

function _autostart() {

  ... all code here ....

}

On the body we will paste all js code what we have to execute at the end of ajax load.

在正文上,我们将粘贴所有 js 代码,我们必须在 ajax 加载结束时执行。

Then we just execute this function by the time trigger. ;)

然后我们只是通过时间触发器来执行这个函数。;)

setTimeout("_autostart();",0000);

And that's all. Done. :)

就这样。完毕。:)

Of course we can use js code function on any event in html code after ajax. For example: 'onchange', 'onclick', etc. It's work too. :)

当然我们可以在ajax之后的html代码中的任何事件上使用js代码函数。例如:'onchange'、'onclick' 等。它也有效。:)