javascript - 我无法在对象构造函数中创建事件监听器来监听
问题描述
当我滚动 div 时,基本上没有任何反应。该方法slideIt
在对象启动时被触发一次,就是这样。它不听滚动事件!为什么会发生这种情况?
function fixed_column_or_row(container_name){
this.container_div=$(container_name);
this.scrollable_div=this.container_div.find(".simplebar-content-wrapper");
this.fixed_row=this.container_div.find(".fixed-row")
this.fixed_column=this.container_div.find(".fixed-column")
//the issue in this line
this.scrollable_div.scroll(this.slideIt())
}
fixed_column_or_row.prototype.slideIt=function(){
var scrollTop = this.scrollable_div.scrollTop(),
scrollLeft = this.scrollable_div.scrollLeft();
console.log("scrollTop")
this.fixed_row.css({
"margin-left": -scrollLeft
});
this.fixed_column.css({
"margin-top": -scrollTop
});
}
解决方案
一个常见的 JavaScript 错误是在需要的是对函数的引用时键入函数调用(通常用于设置事件处理程序,但还有其他类似的情况)。
因此
this.scrollable_div.scroll(this.slideIt());
将调用函数并将this.slideIt()
返回值传递给.scroll
方法,这显然不是我们想要的。()
之后this.slideIt
是造成这种情况的原因,所以没有this.slideIt
是 ()
必要的。
现在,完成后,下一个问题将this
是失去与 to 的关系。Stackoverflow 上有各种各样的问题,其中包含有关其this
工作原理的详细而详尽的答案。 在这里可以说,有必要确保this
正确设置:
this.scrollable_div.scroll(this.slideIt.bind(this));
(还有其他方法可以做到这一点,但这应该可行。)
推荐阅读
- python - 从整个数据框中提取单元格中的字符串
- android - 将信箱模糊应用于 android 相机预览
- youtube-api - 使用 youtube API 从一些 Youtube 频道获取最新视频
- visual-studio - 如何在visual studio 2019上使用winapi创建打开文件资源管理器的按钮
- python - 如何将 pandas 数据帧发送到 flask_restful api?
- twitter - 为什么 tweepy api.search 使用 result_type="popular" 时每页最多只返回 15 条推文?
- sql - 使用窗口函数和过滤器将 1 个特定值返回到所有行
- linux - golang 默认选择哪个加载器
- python - 如何从字典中减去字符串十六进制值?
- python - Python SQL:错误十进制('1367')不是 JSON 可序列化的