为什么没有定义这个javascript函数

Why is this javascript function not defined?

本文关键字:javascript 函数 定义 为什么      更新时间:2023-09-26

我有这个javascript代码:

$(function(){
  var currentCarouselItem = 1; //set carousel to first slide
  var runCarousel = 1;
  $(window).load(function(){    
    setTimeout('autoScroll()', 10000);
  });
  function autoScroll(num){
    if (runCarousel == 1) {
      $('.carouselItem.' + currentCarouselItem).animate({left: '975px'}, 'slow', function(){
        $(this).removeClass('active');
        $(this).attr('style','');
        var nextItem = currentCarouselItem + 1;
        if (nextItem == 7) {
            nextItem = 1;
        }
        $('.carouselItem.' + nextItem).animate({left: '110px'}, 'slow', function(){
          $(this).addClass('active');
        })
      })
    }   
  }
})

每当我运行该站点时,它都会抛出控制台错误:Uncaught ReferenceError: autoScroll is not defined

知道为什么它认为它没有定义吗?

setTimeout('autoScroll()', 10000);

为什么要引用它?

setTimeout(autoScroll, 10000);

这是为初学者准备的。

此外,这里还有范围界定问题。

我可以试着帮你回答,但我认为这家伙做得更好:

JQuery,setTimeout不工作

我认为这是因为autoScroll函数位于最外层$(function(){})创建的闭包内部。因此eval(用于在setTimeout中计算字符串(找不到它,因为它在"全局"范围内运行。

您可以将autoScroll的定义移动到外部。

此外,正如jcolebrand建议的那样,删除引号。

我认为这是因为当您传入一个字符串作为setTimeout()的第一个参数时,javascript基本上从该字符串的全局范围运行eval()autoScroll生活在$(function() { })的范围内,因此无法从全局范围"看到"。

尝试将其更改为setTimeout(autoScroll, 10000);

您的代码有几个问题,但没有定义autoScroll函数的原因是,它是在文档就绪函数的范围内定义的,但在文档就绪超出范围而没有适当的闭包后,通过eval执行。

$('.carouselItem.' + currentCarouselItem).animate({left: '975px'}, 'slow', function(){
                $(this).removeClass('active');
                $(this).attr('style','');
                var nextItem = currentCarouselItem + 1;
                if (nextItem == 7) {
                    nextItem = 1;
                }
                $('.carouselItem.' + nextItem).animate({left: '110px'}, 'slow', function(){
                    $(this).addClass('active');
                });
            });

对于初学者来说,您需要在这样的函数末尾使用分号,