2017-08-03 59 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

謝謝,工作:) –