如果在加载发生后附加事件,则确保在jQuery事件中触发加载代码 [英] Ensuring load code fires in jQuery event if attaching event after load occurs

查看:65
本文介绍了如果在加载发生后附加事件,则确保在jQuery事件中触发加载代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图找出如何最好地将load事件附加到元素,但请确保它已运行。当我绑定到img的load事件时出现问题,但是绑定发生得太晚而且图像已经加载了。是否有一些方法在jQuery中检查图像是否已经加载?

I'm trying to figure out how I can best attach a load event to an element, but be sure that it gets run. The issue comes when I bind to the load event of an img, but that binding happens too late and the image has already loaded. Is there some way in jQuery to check if the image is already loaded?

它显然是一个间歇性的问题,因为有时代码是在图像加载之前运行的,有时它不是。

Its obviously an intermittent issue, because sometimes the code is run before the image loads and sometimes its not.

$(function () {
    var hasRun = false;

    $('#image').bind('load', function () {
        if ($(this).width() <= 0 || $(this).height() <= 0 || hasRun) return;
        hasRun = true;
        // do work here
    }).trigger('load');
});

代码看起来像那样。我添加了hasRun变量并检查变量的高度和宽度以确保其加载,然后添加触发器。

The code looks something like that. I've added the hasRun variable and a check against the height and width of the variable to ensure its loaded, and then added the trigger.

有没有更好的方法做这个?是否有一些我可以用jQuery设置的标志告诉它如果图像已经加载就运行该函数?

Is there a better way to do this? Is there some flag I can set with jQuery to tell it to run the function if the image is already loaded?

推荐答案

你可以使用 .one() .complete 喜欢这样:

You can do this using .one() and .complete like this:

$('#image').one('load', function () {
    if ($(this).width() <= 0 || $(this).height() <= 0 || hasRun) return;
    hasRun = true;
    // do work here
}).each(function() {
  if(this.complete) $(this).trigger('load');
});

.one() 确保处理程序只执行一次。两端的循环检查图像的 .complete 是否为真,例如当它从缓存加载或由于某些其他原因已加载时,如果是真的,触发加载事件... .one()阻止这导致加载代码触发两次结果。

.one() ensures the handler only executes once. The loop at the ends checks if the .complete of the image is true, for example when it loads from cache or has already loaded for some other reason, and if it's true, triggers the load event...the .one() prevents this from causing the load code to fire twice as a result of this.

这篇关于如果在加载发生后附加事件,则确保在jQuery事件中触发加载代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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