简体   繁体   English

如何在jQuery的嵌套函数中调用函数?

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

I have the following jQuery code. 我有以下jQuery代码。 The this.Next() function is throwing a "is not a function" error when called. 调用this.Next()函数时会引发“不是函数”错误。 The this.Next() function is called within the same function as this.countdown(). 在与this.countdown()相同的函数内调用this.Next()函数。 How would I call this.Next() inside the setInterval() nested function? 我将如何在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 's value will change depends on the context where it is called. this的价值会改变取决于它被称为上下文。 You should try as below (I presume your countdown function is in MyObject ) 您应该尝试如下操作(假设您的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...
    }
}

Maybe this is because you have write Next() instead of next() Try writing small 'n'. 可能是因为您编写的是Next()而不是next()尝试编写小的'n'。

Hope this will help you 希望这个能对您有所帮助

Thanks!! 谢谢!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM