How to call function only once in resize function?

て烟熏妆下的殇ゞ 提交于 2020-01-05 03:33:26

问题


Any idea how I can make a function be called only once using .resize, and then have it permanently cancelled or disabled?

$(window).resize(function () {
    if ($(window).width() < 800) {
        size = true;
        mob();
    }
});

UPDATE: Great stuff, thanks sdespont - got it to work with on/off:

$(window).on('resize',function () {
            if ($(window).width() < 800){
                    agent = true;
                    mob();
            }
            });

then turn off the resize function once the condition is met:

$(window).off('resize');

回答1:


Use one function http://api.jquery.com/one/

$(window).one('resize',function () {
    if ($(window).width() < 800){
        size = true;
        mob();
    }
});
$(window).trigger('resize');

Or on/off functions http://api.jquery.com/on/

$(window).on('resize',function () {
    if ($(window).width() < 800){
        size = true;
        mob();
    }
});

$(window).trigger('resize').off('resize');



回答2:


jQuery has the .one method for that:

$(window).one("resize", function () { /* */ });


来源:https://stackoverflow.com/questions/14687459/how-to-call-function-only-once-in-resize-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!