开发者

Why is this javascript function not defined?

I have this javascript code:

$(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');
        })
      })
    }   
  }
})

Whenever I run the site it throws a console error: Uncaught ReferenceError: autoScroll is not defined

Any idea why it thinks it is not defined?


setTimeout('autoScroll()', 10000);

Why put it in quotes?

setTimeout(autoScroll, 10000);

That's for starters.

Additionally, you have scoping issues here.


I could try answering it for you, but I think this guy does a lot better job:

JQuery, setTimeout not working


I think this is because your autoScroll function is inside closure created by outermost $(function(){}). Therefore eval (used to evaluate your string in setTimeout) can't find it, as it runs in a 'global' scope.

You can move the definition of autoScroll outside.

Also, as jcolebrand suggested, remove quotes.


I think it is because when you pass in a string as the first argument for setTimeout() that javascript basically runs eval() from the global scope on that string. autoScroll lives within the scope of $(function() { }) and therefore can't be "seen" from the global scope.

Try changing it to setTimeout(autoScroll, 10000);


There a couple of problems with your code, but the reason that the autoScroll function is not defined is that it defined within the scope of your document ready function, but is executed via eval after the document ready has gone out of scope without the proper closure.


$('.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');

                });
            });

For starters you need a semi colon at the end of functions like this,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜