Javascript 仅在document.ready上附加eventListener
是否有任何方法将事件附加到document.ready?例如,看看这段代码Javascript 仅在document.ready上附加eventListener,javascript,jquery,Javascript,Jquery,是否有任何方法将事件附加到document.ready?例如,看看这段代码 $(document).ready(function(){ $('body').load('eg_pageload.html'); $(document).ajaxStart(function(){ console.log('say something to the console'); }); $('#trigger').on('click', function(){
$(document).ready(function(){
$('body').load('eg_pageload.html');
$(document).ajaxStart(function(){
console.log('say something to the console');
});
$('#trigger').on('click', function(){
$('body').load('file.txt');
});
});
因此,当用户单击触发器时,ajaxStart没有激活。换句话说,ajaxStart只应在页面加载时启动另一个ajax请求时触发,否则不要启动ajaxStart。我尝试在ajaxComplete函数上解除ajaxRequest的绑定,但它不起作用,因为我网站上的某个页面在加载页面时不调用任何ajax请求,而是在单击事件时调用ajax请求。例如。如何使用解除绑定:
$(文档).ready(函数(){
$('body').load('eg_pageload.html')
})) 如果我理解正确,您希望在特定的
Ajax
调用中禁用触发器中的AjaxStart
。这通常是这样做的:
$.ajax({
url: "test.html",
global: false,
...
});
注意global:false,
行。这正是它的用途
从AjaxStart开始
补充说明:
如果在全局选项设置为的情况下调用$.ajax()或$.ajaxSetup()
false,.ajaxStart()方法将不会激发
来自Ajax
全局(默认值:true)类型:布尔值是否触发全局Ajax
此请求的事件处理程序。默认值为true。设置为false以
防止像ajaxStart或ajaxStop这样的全局处理程序被删除
触发。这可以用来控制各种Ajax事件
但是,您正在使用.load()
方法,因此该选项不可用。类似的.get()
方法无法使用它,但这两种方法都是简单的Ajax函数,因此您可以像这样使用Ajax
$(document).ready(function()
$(document).ajaxStart(function(){
console.log('say something to the console');
});
$('#trigger').on('click', function(){
$.ajax({
url: 'file.txt',
global: false,
dataType: 'html'
});
.done(function( html ) {
$( 'body' ).append( html );
});
});
});
这将是避免对该请求执行AjaxStart
的唯一方法,并且无论在DOM
加载中的何处执行该操作都无关紧要
上面的Jquery
就是一个例子,因此它们可能是小错误,但提供的链接将完全涵盖整个过程。为什么不使用on()
和off()
,这只是一个事件
jQuery在内部执行$(document).on('ajaxStart',fn)
,因此您可以使用off()
将其删除,这意味着您可以将事件绑定到ready
回调的顶部,然后在回调结束时将其解除绑定,并且它不会被后续事件触发的ajax调用
$(document).ready(function(){
$(document).on('ajaxStart', ajaxFN); // place at start
function ajaxFN(){
console.log('say something to the console');
}
$('body').load('eg_pageload.html'); // this will trigger ajaxStart
$('#trigger').on('click', function(){
$('body').load('file.txt'); // this will NOT
});
$(document).off('ajaxStart', ajaxFN); // place at end
});
如果我理解正确,您只想在文档准备好之前执行名为initiated ebe的Ajax的
ajaxStart
回调?我已经更新了这个问题,请参阅。我根本不明白,只在页面加载期间完成的请求上启动ajaxStart,但是在pageload上没有任何ajax请求?在我的实际代码中,在pageload上有ajax调用,这只是一个例子。我应该粘贴我的实际代码吗?您可以查看$的global:false
选项。ajax({global:false,…})
这会不会导致AjaxStart
在打算使用它的后续ajax
请求中不会被调用?谢谢,它正在工作。虽然我改变了这个问题的某些部分以符合我的需要:D
$(document).ready(function(){
$(document).on('ajaxStart', ajaxFN); // place at start
function ajaxFN(){
console.log('say something to the console');
}
$('body').load('eg_pageload.html'); // this will trigger ajaxStart
$('#trigger').on('click', function(){
$('body').load('file.txt'); // this will NOT
});
$(document).off('ajaxStart', ajaxFN); // place at end
});