如何将窗口大小调整值传递给另一个函数

时间:2014-11-21 16:57:01

标签: javascript jquery

我正在尝试学习如何在窗口调整大小事件中传递一个值到函数,但我不知道我做错了什么。基本上每次窗口调整大小时,我都希望scrollHeight转到另一个函数,我可以在点击时查看该值。

$(window).on('resize', function(){
var mheight = $('#wrapper')[0].scrollHeight;
smoothscroll(mheight);
});

function smoothscroll(mvalue) {
$mheight = this.mvalue;

if ($mheight < 3000) {
$(selector).on('click',function() {
console.log('show me my latest scroll height value for larger screens' + $mheight);
});
} else {
console.log('show me my current scroll height value for smaller screens' + $mheight);
}

}

...但由于某种原因,我的价值总是以未定义的方式出现......

1 个答案:

答案 0 :(得分:1)

更改

function smoothscroll(mvalue) {
   $mheight = this.mvalue;
   ....
}

function smoothscroll(mvalue) {
   $mheight = mvalue; // you don't need `this`, cause mvalue has passed by argument
   ....
}

实际上,您可以直接使用mvalue而不将其缓存到$mheight

完整代码:

$(window).on('resize', function () {
    var mheight = $('#wrapper')[0].scrollHeight;
    smoothscroll(mheight);
});

function smoothscroll(mvalue) {
    if (mvalue < 3000) {
        $(selector).on('click', function () {
            console.log('show me my latest scroll height value for larger screens' + mvalue);
        });
    } else {
        console.log('show me my current scroll height value for smaller screens' + mvalue);
    }

}