簡體   English   中英

如何在jQuery的嵌套函數中調用函數?

[英]How do I call a function from within a nested function in jQuery?

我有以下jQuery代碼。 調用this.Next()函數時會引發“不是函數”錯誤。 在與this.countdown()相同的函數內調用this.Next()函數。 我將如何在setInterval()嵌套函數中調用this.Next()?

this.countdown = function(element) {
  interval = setInterval(function() {
    var el = document.getElementById(element);
    if(seconds == 0) {
      if(minutes == 0) {
        alert(el.innerHTML = "Your time for this section has expired");                    
        clearInterval(interval);

        // Send user to the next section
        return this.Next();
      } else {
        minutes--;
        seconds = 60;
      }
    }
    if(minutes > 0) {
      var minute_text = minutes + ' min';
    } else {
      var minute_text = '';
    }
    var second_text = 'sec';
    el.innerHTML = 'Your time: ' + minute_text + ' ' + seconds + ' ' + second_text;
    seconds--;
  }, 1000);       
};

this的價值會改變取決於它被稱為上下文。 您應該嘗試如下操作(假設您的countdown功能在MyObject

function MyObject() {
    var self = this; // add this declaration and instead of this key word, you can use self
    self.countdown = function (element) {
        ....blah blah blah...


        return self.Next(); // instead of this.Next(), you use self.Next()
        ....blah blah blah...
    }
}

可能是因為您編寫的是Next()而不是next()嘗試編寫小的'n'。

希望這個能對您有所幫助

謝謝!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM