将两个事件处理组合到一个事件处理中

时间:2014-07-04 22:21:15

标签: javascript jquery optimization

我正在尝试将两个相同的代码组合在一起,它们只在事件处理程序中有所不同。当网站加载时,它会激活我的功能,如果用户调整浏览器的大小,它将更新变量并再次运行该功能。

$(window).load(function() {

        $(!agent) {

            var milk   = $().height(),
                choco  = $().width();

            doThis();

        } else {
            var orange  = $().length(),
                apple   = $().width();

            orThis();
        }

});

$(window).resize(function() {

        $(!agent) {

            var milk   = $().height(),
                choco  = $().width();

            doThis();

        } else {
            var orange  = $().length(),
                apple   = $().width();

            orThis();
        }

});

2 个答案:

答案 0 :(得分:2)

或者您可以定义功能:

function mySuperDuperEventHandler()
{
    $(!agent) {

        var milk   = $().height(),
            choco  = $().width();

        doThis();

    } else {
        var orange  = $().length(),
            apple   = $().width();

        orThis();
    }
}

然后将其指定为事件处理程序:

$(window).on('load resize',mySuperDuperEventHandler);

答案 1 :(得分:1)

您可以将多个事件与on()侦听器合并。

$(window).on('load resize',function() {

        $(!agent) {

            var milk   = $().height(),
                choco  = $().width();

            doThis();

        } else {
            var orange  = $().length(),
                apple   = $().width();

            orThis();
        }

});