函数未定义,无法加载源jQuery

ben*_*e89 0 jquery

我有这个jquery代码:

$(document).ready(function() {
            function slideSwitch() {
                var $active = $('#slideShow IMG.active');

                if ( $active.length == 0 ) $active = $('#slideShow IMG:last');

                var $next =  $active.next().length ? $active.next()
                    : $('#slideShow IMG:first');

                $active.addClass('last-active');

                $next.css({opacity: 0.0})
                    .addClass('active')
                    .animate({opacity: 1.0}, 1000, function() {
                        $active.removeClass('active last-active');
                    });
            }


                setInterval( "slideSwitch()", 5000 );

        });
Run Code Online (Sandbox Code Playgroud)

并且它没有定义slideSwitch()的错误?有任何想法吗?

Guf*_*ffa 5

如果您使用字符串,setInterval它将在window对象的范围内被评估,并且当您在另一个函数中本地声明该函数时,它在全局范围内不可用.

只需使用函数名称而不是带有调用函数的代码的字符串:

window.setInterval(slideSwitch, 5000);
Run Code Online (Sandbox Code Playgroud)

这将传递对函数的引用而不是字符串,因此它在调用时不依赖于函数的名称.