在ajax post之后执行document.ready

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

您可以随时将所有内容放在一个函数中(命名为loadfunction或其他),并在文档加载时调用该函数,并在加载ajax时再次调用该函数。 虽然它是一个被黑客攻击的解决方案,但它应该运行得很好。

然后取出$(document).onready(function () {和它的end bracket }并将它放在function OnloadFunction () { with } 。然后放入$document.onready(OnloadFunction);

示例:你有

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

它会变成:

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

然后你可以随时调用OnloadFunction

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

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

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

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

我已成功使用如下模式:

首先,我们必须定义一个.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的所有痛苦。 它允许我维护一组init例程,并专注于有趣的事情。

我用了一些技巧。 ;)所有代码都在文件(ajax)的加载部分内。 我没有使用jquery ajax load的任何“成功”,“完成”等扩展function。

首先,我们必须建立任何function。 例如:_autostart();

 function _autostart() { ... all code here .... } 

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

然后我们只是通过时间触发器执行此function。 ;)

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

就这样。 完成。 🙂

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