2017-08-03 61 views
0

我有问题,我无法理解:通话功能的JavaScript

var Copyright = 
{ 

    onLoad: function() { 
     this.initCopyrightMoving(); 
    }, 


    initCopyrightMoving: function() { 
     $(".sidebar_toggle").click(function() { 
      var copyright = document.getElementById("copyright-text"); 

      if (copyright.className == "copyright-menu-open") { 
       this.decrease(280, 80, 10, copyright); 
      } 

      else 
       copyright.className = "copyright-menu-open" 

     }); 
    }, 

    decrease: function (actual_val, stop_val, step, copyright) { 
     setTimeout(function() { 
      if (actual_val == stop_val) { 
       copyright.className = "copyright-menu-closed"; 
      } 
      actual_val = actual_val - step; 
      copyright.style.paddingLeft = parseInt(actual_val) + "px"; 
      this.decrease(actual_val, stop_val, step, copyright); 
     }, 10); 
    } 

}; 

,当我在行this.decrease(280, 80, 10, copyright);打电话initCopyrightMoving,我得到这个错误:

copyright.js:14 Uncaught TypeError: this.decrease is not a function 
    at HTMLAnchorElement.<anonymous> (copyright.js:14) 
    at HTMLAnchorElement.dispatch (jquery-1.11.2.min.js:3) 
    at HTMLAnchorElement.r.handle (jquery-1.11.2.min.js:3) 

可以SM告诉我我做错了什么?还因为我不能运行脚本的下一部分,你能告诉我,如果decrease函数写得不错,我的意思是它会正常运行。

回答

0

this这是您单击的元素$(".sidebar_toggle")

尝试jQuery的处理程序之前定义var self = this;并调用self.decrease内处理

this.decreasesetTimeout也不会类似工作的原因所在。修复是相同的

0

这是因为this(上下文)在click回调中发生更改。阻止错误的一种方法是保留this的副本并在回调中使用该副本。

initCopyrightMoving: function() { 

    var _this = this; // some developers use `self` 

    $(".sidebar_toggle").click(function() { 
    var copyright = document.getElementById("copyright-text"); 
    if (copyright.className == "copyright-menu-open") { 
     _this.decrease(280, 80, 10, copyright); 
    } else { 
     copyright.className = "copyright-menu-open" 
    } 
    }); 
}, 

Here's a useful article关于JavaScript中的范围和上下文。

+1

谢谢,工作:) –