为了账号安全,请及时绑定邮箱和手机立即绑定

我无法在对象构造函数中创建一个事件监听器来监听

我无法在对象构造函数中创建一个事件监听器来监听

绝地无双 2021-06-21 16:45:38
当我滚动 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      }); }
查看完整描述

1 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

一个常见的 JavaScript 错误是在需要引用函数时输入函数调用(通常用于设置事件处理程序,但也有其他类似的情况)。

因此

  this.scrollable_div.scroll(this.slideIt());

调用this.slideIt()函数和返回值传递给.scroll方法,那显然不是什么需要。在()this.slideIt是什么原因造成这一点,所以this.slideIt 没有 ()必要。

现在,完成后,下一个问题将是 与 的关系this将丢失。Stackoverflow 上有各种各样的问题,其中有关于this工作原理的详尽而详尽的答案。 这里只想说,有必要确保this正确设置:

  this.scrollable_div.scroll(this.slideIt.bind(this));

(还有其他方法可以做到,但这应该可行。)


查看完整回答
反对 回复 2021-06-24
  • 1 回答
  • 0 关注
  • 224 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信