[英]How to update some global variables used in 'scroll' event when 'resize' event is fired in JQuery / Javascript?
I have some variables globally declared: 我有一些全局声明的变量:
var a = $('.ela');
var b = $('.elb');
var top_a = $('.ela').offset().top;
var top_b = $('.elb').offset().top;
I use these variables on "scroll" event applied to the <main>
element: 我在应用于
<main>
元素的“ scroll”事件上使用了这些变量:
$('main').on('scroll', function(top_a, top_b) {
// do something with top_a and top_b
}
Now, I need to use the updated values of these variables at the event $(window).resize(), so I write: 现在,我需要在事件$(window).resize()上使用这些变量的更新值,所以我这样写:
$(window).resize(function() {
top_a = $('.ela').offset().top;
top_b = $('.elb').offset().top;
})
This way the global variables are updated, but in $('main').on('scroll', function etc) I get the old values... 这种方式全局变量被更新,但是在$('main')。on('scroll',function etc)中,我得到了旧值...
Where am I doing wrong? 我在哪里做错了?
You are not passing the variables to scroll
event at 您没有将变量传递给
scroll
事件
$('main').on('scroll', function(top_a, top_b) {
// do something with top_a and top_b
})
top_a
would reference the event
object, not top_a
variable. top_a
将引用event
对象,而不是top_a
变量。
You can pass the variables using event.data
您可以使用
event.data
传递变量
$('main').on('scroll', {top_a:top_a, top_b:top_b}, function(event) {
// do something with top_a and top_b
console.log(event.data.top_a, event.data.top_b)
});
or, directly by referencing the variables 或者,直接通过引用变量
$('main').on('scroll', function(event) {
// do something with top_a and top_b
console.log(top_a, top_b)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.