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



当我滚动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的关系将丢失。关于Stackoverflow有各种各样的问题,关于this如何工作的长而彻底的答案。 这里只需说明一下,需要确保正确设置this

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

(还有其他方法可以做到这一点,但这应该有效。

最新更新