ajax post后执行document.ready

发布于 2024-10-31 06:58:03 字数 209 浏览 5 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

睡美人的小仙女 2024-11-07 06:58:03

您始终可以将所有内容放入一个函数(名为 loadfunction 或其他名称)中,并在文档加载时调用该函数,并在加载 ajax 时再次调用该函数。虽然它是一个拼凑在一起的解决方案,但它应该工作得足够好。

然后取 $(document).onready(function () { 及其结束括号 } 之间的所有内容
并将其放入以}结尾的function OnloadFunction () {中。
然后放入 $document.onready(OnloadFunction);

示例:
你有

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

它会变成:

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

然后你可以随时调用 OnloadFunction

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.

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

Example:
You have

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

It would turn into:

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

Then you can call OnloadFunction whenever you want to.

邮友 2024-11-07 06:58:03

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

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

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

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

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

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

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

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

最佳男配角 2024-11-07 06:58:03

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

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

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

$( document ).ajaxComplete(function() {
    $( ".log" ).text( "Triggered ajaxComplete handler." );
});
我只土不豪 2024-11-07 06:58:03

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

首先我们必须定义一个 .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, '$1') ),
        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);
  };

然后,我们编写 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...

  });

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

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

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

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

I've successfully used a pattern like the following:

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

// 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, '$1') ),
        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...

// 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 domupdated event and pass the updated DOM fragment as a parameter - like so:

...
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.

万人眼中万个我 2024-11-07 06:58:03

肯·麦克的回答略有不同。无论出于何种原因,我的 ajaxComplete 都不会触发,除非它嵌套在 document.ready 中。把它放在里面并仍然大声叫对我来说很有效。

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

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

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

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.

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

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

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

隐诗 2024-11-07 06:58:03

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

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

function _autostart() {

  ... all code here ....

}

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

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

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

仅此而已。完毕。 :)

当然我们可以在ajax之后对html代码中的任何事件使用js代码函数。
例如:“onchange”、“onclick”等。
这也是工作。 :)

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.

First we must build any function.
For Example: _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.

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. :)

棒棒糖 2024-11-07 06:58:03

我尝试了 Jess、Ken Mc 和 byork2005 的答案,但没有任何效果。对我有用的唯一方法是使用 jquery 的 .trigger 函数。为此,必须使用 .on 调用“就绪”处理程序。这使得以后可以手动触发事件。请参阅.trigger 文档

$(document).on('ready myFunction',function(){
    (blah blah)
    Rails.ajax({
        (blah blah)
        success: function(result) {
          $(document).trigger('myFunction');
        }
    });
});

$(document).trigger('myFunction');

现在,myFunction 在文档就绪和成功的 ajax 调用时都会被触发。触发该功能的另一种方法是

$(document).trigger('myFunction');

在页面上的任何位置,甚至在控制台中使用。请注意这一点,并考虑安全性。

I tried Jess's, Ken Mc's, and byork2005's answers, and nothing worked. The only method that worked for me was to user jquery's .trigger function. For that, the 'ready' handler must be called with .on. That makes it possible to later trigger the event manually. See the docs for .trigger.

$(document).on('ready myFunction',function(){
    (blah blah)
    Rails.ajax({
        (blah blah)
        success: function(result) {
          $(document).trigger('myFunction');
        }
    });
});

$(document).trigger('myFunction');

Now myFunctionis triggered both on document ready, and on successful ajax calls. Another way to trigger the function is to use

$(document).trigger('myFunction');

anywhere on the page, or even in the console. Be aware of this, and think about security.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文