jQuery函数在文档准备就绪时调用了2次 [英] jQuery Function called 2 times on document ready

查看:103
本文介绍了jQuery函数在文档准备就绪时调用了2次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有那个jQuery代码:

I have that jQuery code:

$(function () {

    (function checkWidthOnResize() {
        $(window).on('resize', function () {
            if($(window).width() < 769){
                alert('asdads');
            }
            return false;
        });
    }());

    (function checkWidth() {

        if($(window).width() < 769){
            alert('asddsa');
        }
        return false;
    }());

});

当页面准备好并且我尝试在769px下调整屏幕大小时,我的第一个函数checkWidthOnResize()被加载了两次.换句话说,我收到2条警报消息,一个接一个.

When page is ready and I try to resize the screen under 769px, my first function checkWidthOnResize() is loaded two times. In other words I am getting 2 alert messages, one after another.

我想了解为什么会这样,并知道如何预防呢?

I would like to understand why this is happening and know how can I prevent it?

推荐答案

问题与jQuery不相关.取决于浏览器何时调用 window.onresize 事件.使用以下代码,您将获得相同的结果:

The problem is not related to jQuery. It depends on the browser when to call the window.onresize event. You will get the same result with this code:

$(function () {
    window.onresize = function() {
        if($(window).width() < 769) {
            alert('asdads');
        }
    };
});

doc 引用:

由于调整大小的事件可以以很高的速率触发,因此事件处理程序 不应该执行计算量大的操作,例如DOM 修改.相反,建议使用 requestAnimationFrame,setTimeout或customEvent,如下所示:

Since resize events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame, setTimeout or customEvent, as follows:

这篇关于jQuery函数在文档准备就绪时调用了2次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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