首页 > 解决方案 > 我无法在对象构造函数中创建事件监听器来监听

问题描述

当我滚动 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
      }); 

}

标签: javascriptjqueryjavascript-objects

解决方案


一个常见的 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));

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


推荐阅读