简体   繁体   English

为什么在加载而不是在窗口调整大小时触发此on('resize')事件?

[英]Why is this on('resize') event triggered at load and not on window resize?

I have the following code wrapped in $(document).ready(function(){}); 我将以下代码包装在$(document).ready(function(){}); :

var sizeMapContainer = function(n) {
    var w = $(window).innerHeight();
    var h = $('#sl-header-container').outerHeight();
    var f = $('.oev-form-container').outerHeight();
    var m = w - h - f;
   $('#map-container').outerHeight(m);
}
sizeMapContainer(1);
$(window).on('resize', sizeMapContainer(2));

Why is it that sizeMapContainer gets called twice when the page loads but not when I resize the window? 为什么在页面加载时调用sizeMapContainer两次,但是在调整窗口大小时却没有调用两次?

You're calling the function, not binding the event to the function. 您正在调用函数,而不是将事件绑定到函数。 It should be: 它应该是:

$(window).on('resize', function() {
    sizeMapContainer(2);
});

This is the line with the issue 这就是问题所在

$(window).on('resize', sizeMapContainer(2));

The second argument to 'on' is a function that will be run when the 'resize' event occurs. “ on”的第二个参数是将在“ resize”事件发生时运行的函数。 It's not expecting to be called with your (2) at the end. 预计不会在您的(2)结尾处调用它。 It's running your function sizeMapContainer() on the spot, rather than letting the 'resize' event decide when it happens. 它是当场运行您的sizeMapContainer()函数,而不是让'resize'事件决定何时发生。 If you remove the (2) you'll get the sizeMapContainer() function firing when you resize. 如果删除(2),则在调整大小时会触发sizeMapContainer()函数。

function myName(){
    return "Aaron";
}

console.log( myName ); //gives you the function itself
console.log( myName() ); //gives you Aaron

So what he did was create an anonymous function that runs your function and passes the argument for you. 因此,他所做的就是创建一个匿名函数,该函数运行您的函数并为您传递参数。

Hope that helps clear things up. 希望这有助于清理问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM