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

时间:2017-10-02 03:19:09

标签: jquery function nested this

我有以下jQuery代码。 this.Next()函数在调用时抛出“不是函数”错误。 this.Next()函数在与this.countdown()相同的函数中调用。我如何在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);       
};

2 个答案:

答案 0 :(得分:2)

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...
    }
}

答案 1 :(得分:0)

也许这是因为你写了Next()而不是next() 尝试写小' n'

希望这会对你有所帮助

谢谢!

相关问题