jQuery结合.ready和.resize [英] jQuery combine .ready and .resize

查看:160
本文介绍了jQuery结合.ready和.resize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的jQuery .ready函数中,我的部分代码(几乎几乎全部)在调整窗口大小时也适用,因为它是布局工作.但是,由于它是相同的代码,我如何才能组合"这两个函数,以使我的代码不会重复自身(并且难以维护)?

Some (well, nearly all) of my code that is in my jQuery .ready function also applies when the window is resized, as it's layout work. However, since it's the same code, how could I "combine" the two functions, so that my code doesn't repeat itself (and be a mess to maintain)?

谢谢!

推荐答案

$(document).ready(myfunction);
$(window).on('resize',myfunction);

function myfunction() {
    // do whatever
}

另一种技术是在另一个事件内.trigger()一个事件:

Another technique is to .trigger() one event inside the other:

$(window).on('resize',function() {
    // do whatever
});
$(document).ready(function() {
    $(window).trigger('resize');
});

如果您将代码放在页面底部以避免使用$(document).ready,它将变得更加简单:

If you put your code at the bottom of the page to avoid needing $(document).ready, it gets even simpler:

$(window).on('resize',function() {
    // do whatever
}).trigger('resize');

这篇关于jQuery结合.ready和.resize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆