似乎无法获得jquery resize事件来处理Modernizr媒体查询function

我正在尝试在以下函数上激活resize事件:

$(function() { if (Modernizr.mq('only screen and (min-width: 1140px)')) { $('div#ss1').html('
[snip]
'); $('div#ss1').append('
'); } if (Modernizr.mq('only screen and (max-width: 1139px)')) { $('div#ss2').html('
[snip]
'); $('div#ss2').append('
'); } });

我想为它添加一个resize的侦听器。 基于http://api.jquery.com/resize/我将第一行更改为$(window).resize(function()但是整个函数停止工作。

我究竟做错了什么? 谢谢。

更新:基于这个Paul Irish post,我将smartresize添加到我的plugins.js。 我将函数调用从$(function()更改$(window).smartresize(function()并且它停止工作。将其更改回$(function()并再次工作。为什么我不能添加resize事件这个吸盘的任何类型的听众?:-)

这里要理解的关键点是$(function() {})正在做什么。 在文档准备好之前,它内部的代码不会执行。 将代码放入其中相当于将代码放入:

 $(document).ready(function () { //here }) 

你想把你的resize事件放在$(function() {}) ,如下所示:

 function checkMq() { if (Modernizr.mq('only screen and (min-width: 1140px)')) { $('div#ss1').html('
[snip]
'); $('div#ss1').append('
'); } if (Modernizr.mq('only screen and (max-width: 1139px)')) { $('div#ss2').html('
[snip]
'); $('div#ss2').append('
'); } } $(function() { // the call to checkMq here will execute after the document has loaded checkMq(); $(window).resize(function() { // the call to checkMq here will execute every time the window is resized checkMq(); }); // you can add other listeners here click, hover, etc. });

如果您只使用$(window).resize(function() {})而不使用$(function() {}) ,它将无法工作,因为该文档尚未准备就绪,也不是准备好添加任何事件监听器。