为什么没有定义这个javascript函数?
我有以下javascript代码:为什么没有定义这个javascript函数?,javascript,jquery,debugging,undefined,Javascript,Jquery,Debugging,Undefined,我有以下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)
$(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');
})
})
}
}
})
每当我运行站点时,它都会抛出一个控制台错误:uncaughtreferenceerror:autoScroll未定义
知道为什么它认为它没有定义吗
setTimeout('autoScroll()', 10000);
为什么要加引号
setTimeout(autoScroll, 10000);
这是一开始
此外,这里还存在范围界定问题
$('.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');
});
});
对于初学者来说,在这样的函数末尾需要一个分号,我认为这是因为您的
autoScroll
函数位于由最外层的$(function(){})
创建的闭包内部。因此eval(用于在setTimeout
中评估字符串)找不到它,因为它在“全局”范围内运行
您可以将autoScroll
的定义移到外部
另外,正如jcolebrand所建议的,删除引号。我认为这是因为当您传入一个字符串作为
setTimeout()
的第一个参数时,javascript基本上是从该字符串的全局范围运行eval()
autoScroll
位于$(function(){})
的范围内,因此无法从全局范围“查看”
尝试将其更改为
setTimeout(autoScroll,10000)代码>我可以试着帮你回答,但我认为这家伙做得更好:
您的代码有几个问题,但是没有定义自动滚动
功能的原因是它在您的document ready函数的范围内定义,但是在document ready超出范围而没有正确关闭后,通过eval执行。范围问题。。只需将函数放在$(function()
之外,它就可以工作了。这种可能的重复通常是好的做法,但不会改变这种情况下的行为。这听起来像是“像重复一样接近”