【问题标题】:How do I call a function from within a nested function in jQuery?如何从 jQuery 的嵌套函数中调用函数?
【发布时间】:2018-03-13 03:25:48
【问题描述】:

我有以下 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);       
};

【问题讨论】:

  • 因为范围不正确。 setInterval 中的 this 是 setInterval 本身,而不是对象。堆栈上有很多这样的问题,试着在那里找到答案。

标签: jquery function nested this


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    也许这是因为你写的是 Next() 而不是 next() 尝试写小“n”。

    希望对你有帮助

    谢谢!!

    【讨论】:

      猜你喜欢
      • 2012-02-23
      • 2018-05-27
      • 2010-11-05
      • 2021-11-07
      • 1970-01-01
      • 2012-11-20
      • 2015-05-24
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多