【问题标题】:jQuery not firing on load/ready when server responce is slow当服务器响应缓慢时,jQuery 不会在加载/就绪时触发
【发布时间】:2013-10-03 16:00:14
【问题描述】:

我在 jQuery(document).ready() 和 jQuery(window).load() 上触发了一个函数。两者功能相同。它应该触发图像调整大小脚本。

但是,有时,当服务器响应缓慢时,页面加载完成后脚本根本不会触发。

这个问题我已经有很长一段时间了,也许它有点矫枉过正,但现在,我在文档准备和窗口加载中调用如下所示的函数:

    jQuery('img', '.background').each(function(){
        jQuery(this).load(function(){
            jQuery(this).resizeImage();
        });
    });

它调用的函数是:

jQuery.fn.resizeImage = function() {
console.log('fired');
var bgImg = jQuery(this);

/* get img sizes */
var imgwidth = bgImg.width();
var imgheight = bgImg.height();

/* get window sizes */
var winwidth = jQuery(window).width();
var winheight = jQuery(window).height();
/* get the ratio, checks wether window is bigger or smaller than the image */
var widthratio = winwidth / imgwidth;
var heightratio = winheight / imgheight;
/* checks the difference */
var widthdiff = heightratio * imgwidth;
var heightdiff = widthratio * imgheight;
/* if you want the entire image to always fit the screen, change the > to < */
if(heightdiff>winheight) { 
    bgImg.css({
        width: winwidth+'px',
        height: heightdiff+'px',
        marginLeft: '-'+winwidth/2+'px'
    });
} else {
    bgImg.css({
        width: widthdiff+'px',
        height: winheight+'px',
        marginLeft: '-'+widthdiff/2+'px'
    });     
}
};

使用console.log,我发现这个函数根本没有触发。

谁能指出我正确的方向,为什么这可能行不通?

【问题讨论】:

  • 将脚本保留在页面底部。就在&lt;/body&gt;标签上方

标签: javascript jquery html


【解决方案1】:

猜你错过了this

   jQuery('img', '.background').each(function(){
        var $self = $(this);
        $self.load(function(){
            $self.resizeImage();
        });
    });

【讨论】:

  • 我试过了,但是代码根本不起作用。我真的不明白为什么它会有所不同,因为唯一的区别是你将 jQuery(this) 存储在一个变量中,我只是直接使用它。
【解决方案2】:

自己解决了。

问题如下:

jQuery(window).load(function(){
    jQuery('img', '.background').each(function(){
        jQuery(this).load(function(){
            jQuery(this).resizeImage();
        });
    });
});

由于双重加载(jQuery(window).load 和 jQuery(this).load),代码根本没有执行。由于加载窗口时,图像也已经加载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2015-04-10
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多