Javascript - 取消 onload 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3717205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:01:41  来源:igfitidea点击:

Javascript - Cancel onload event

javascriptjqueryeventsonload

提问by Somebody

    var town_imgs = $('.town_img img');
    var container;
    var imggg
    town_imgs.hover(function(){

        container = $('<div class="town_img_thmb">'
                +'<span class="thmb_container ajax2"></span>'
            +'</div>').appendTo($(this).parents('.town_wrapper').find('.thmb_wrapper'));

        var imggg = new Image(140,100);             
        imggg.onload = function(){
            container.find('.thmb_container').append(this);
        }
        imggg.src = $(this).attr('src').replace(/\/t0\//,'/t1/');               

    },function(){

        container.remove();
        $(imggg).unbind('onload');

    });

Isn't working when I'm hovering thumbnails very fast. It displays 2-3 images in a row for a about 250-500ms~

当我快速悬停缩略图时不起作用。它连续显示2-3张图像约250-500ms~

As I understand it happens because I'm using outside variable to store current thumbnail.

据我了解,这是因为我使用外部变量来存储当前缩略图。

Is it?

是吗?

Is there solution to cancel onload event properly?

是否有正确取消 onload 事件的解决方案?

Thanks ;)

谢谢 ;)

回答by Nick Craver

There are 2 problems, you want to remove varfrom this, so your reference is correct:

有2个问题,你想从中删除var,所以你的参考是正确的:

var imggg = new Image(140,100);

Then unbind by clearing the onloadfunction you set:

然后通过清除onload您设置的功能解除绑定:

imggg.onload = null;

You can see a working demo here.

您可以在此处查看工作演示