Javascript 移动到其他页面时滚动$(窗口)面临问题
我在“滚动”事件中遇到$window.on问题。 它在一个页面中运行良好,但即使我转到另一个页面,它也会继续运行。我在Ngondestory中销毁了它,但它仍在运行Javascript 移动到其他页面时滚动$(窗口)面临问题,javascript,jquery,angular,Javascript,Jquery,Angular,我在“滚动”事件中遇到$window.on问题。 它在一个页面中运行良好,但即使我转到另一个页面,它也会继续运行。我在Ngondestory中销毁了它,但它仍在运行 ngOnInit() { this.onScrollEvent = $(window).on('scroll', function() { console.log('scroll: '); }); } ngOnDestroy() { if (this.onSc
ngOnInit() {
this.onScrollEvent = $(window).on('scroll', function() {
console.log('scroll: ');
});
}
ngOnDestroy() {
if (this.onScrollEvent) {
this.onScrollEvent.unsubscribe();
}
}
你把jQuery和Angular搞混了,这首先是一个糟糕的做法。另外,on方法不返回订阅。相反,您必须在jQuery中使用.off方法 无论如何,我建议您在组件中使用Angular的HostListener装饰器。仅当零部件处于活动状态时,此选项才会处于活动状态:
@HostListener("window:scroll", [])
onWindowScroll() {
console.log("We're scrolling!");
}
请提供遇到问题的代码的stackblitz示例