使用jQuery绑定准备和调整大小.on() [英] Bind to ready and resize at same time using jQuery .on()
问题描述
这可以在准备和调整大小上运行相同的代码:
This works for running the same code on both ready and resize:
$(document).ready(function() {
$(window).resize(function() {
// Stuff in here happens on ready and resize.
}).resize(); // Trigger resize handlers.
});//ready
如何使用 jQuery.on()完成相同的结果?
How would you accomplish the same result using jQuery.on() ?
推荐答案
on
可用于连接调整大小和就绪事件,就像任何其他事件一样
on
can be used to wire up the resize and ready events just like any other event.
所以对于你的情况,你可以创建一个函数,它具有你想要发生的代码 resize
准备好
,然后将其传递给上的两个电话。
So for your case, you could create a function that has the code you want to happen for resize
and ready
, and then pass it to both calls to on
.
如果要保持封闭范围的清洁,可以立即执行所有功能:
If you want to keep your enclosing scope clean, you could do all this in an immediately executing function:
(function() {
function stuffForResizeAndReady(){
// Stuff in here happens on ready and resize.
}
$(window).on("resize", stuffForResizeAndReady);
$(document).on("ready", stuffForResizeAndReady);
})();
2012-07-25 :有两个不同之处要注意当使用 .on()
附加准备好的处理程序:
2012-07-25: There are 2 differences to be aware of when using .on()
to attach ready handlers:
-
准备通过
$(fn)
和$(document).ready(fn)
添加的处理程序由.on()
添加的不是。使用这些,如果在DOM加载之后添加一个处理程序,fn将被立即触发。如果您在加载DOM之后,通过.on('ready',fn)
添加处理程序,那么将不会被jQuery触发,但您可以手动.trigger('ready')
。
Ready handlers added via
$(fn)
and$(document).ready(fn)
are "retro-fired" while ones added by.on()
are not. Using those, if you add a handler after the DOM is already loaded, the fn will be fired immediately. If you add a handler via.on('ready', fn)
after the DOM is loaded, it will not be fired by jQuery, but you can manually.trigger('ready')
it.
当您使用 $(fn)
或 $(文档) ready(fn)
添加一个可以处理的程序,fn接收 jQuery 作为其第一个参数,允许familar jQuery(function($){})
usage。如果您使用 $(document).on('ready',fn)
,则fn收到的第一个参数是 事件对象 。在这两种情况下,这个这个
在fn里面是文件
。如果你要做一些异常的事情,例如 $('#foo')。on('ready',fn)
为了触发,
将是 #foo
元素。
When you use $(fn)
or $(document).ready(fn)
to add a ready handler, the fn receives jQuery as its 1st arg, allowing the familar jQuery(function($){ })
usage. If you use $(document).on('ready', fn)
, the 1st arg that the fn receives is an event object. In both cases this
inside the fn is the document
. If you were to do something abnormal like $('#foo').on('ready', fn)
for the purpose of triggering, this
would be the #foo
element.
这篇关于使用jQuery绑定准备和调整大小.on()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!