繁体   English   中英

函数未捕获的referenceError

[英]Uncaught referenceError on a function

我正在遵循一个简单的教程,希望可以构建一个响应式滑块,但是它一直告诉我控制台中存在一个错误,指向一个名为advance()的函数

这是滑块的简单html:

<div class="slider">
<div class="slide-viewer">
    <div class="slide-group">
        <div class="slide slide-1">1</div>
        <div class="slide slide-2">2</div>
        <div class="slide slide-3">3</div>
        <div class="slide slide-4">4</div>
    </div>
</div>
</div>
<div class="slide-buttons"></div>

这是JS-脚本文件之前已包含JQuery,所以我知道这不是问题所在,但是当我单击按钮时,它向我显示了控制台中的错误:

$(document).ready(function(){
$('.slider').each(function(){
    var $this = $(this);
    var $group = $this.find('.slide-group');
    var $slides = $this.find('.slide');
    var buttonArray = [];
    var currentIndex = 0;
    var timeout;

    function advance(){
        clearTimeout(timeout);

        timeout = setTimeout(function(){
            if (currentIndex < ($slides.length - 1) ){
                move(currentIndex + 1);
            } else {
                move(0);
            }
        }, 4000);
    }

    $.each($slides, function(index){
        var $button = $('<button type="button" class="slide-btn">&bull;</button>');
        if(index === currentIndex) {
            $button.addClass('active');
        }
        $button.on('click', function(){
            move(index);
        }).appendTo('.slide-buttons');
        buttonArray.push($button);
    });

advance();

});

function move(newIndex) {
    var animateLeft, slideLeft;

    advance();

    if ($group.is(':animated') || currentIndex === newIndex) {
        return;
    }

    buttonArray[currentIndex].removeClass('active');
    buttonArray[newIndex].addClass('active');

    if (newIndex > currentIndex) {
        slideLeft = '100%';
        animateLeft = '-100%';
    } else {
        slideLeft = '-100%';
        animateLeft = '100%';
    }

    $slides.eq(newIndex).css( {left: slideLeft, display: 'block'} );
    $group.animate( {left: animateLeft} , function() {
        $slides.eq(currentIndex).css( {display: 'none'} );
        $slides.eq(newIndex).css( {left: 0} );
        $group.css( {left: 0} );
        currentIndex = newIndex;
    });
}
});

它告诉我问题出在Js的第40行,它指向您第二次在脚本中看到advance() 任何帮助将不胜感激,因为我已经不得不修改代码,因为其中一些失败了,但这让我很沮丧! 当然,Js不是我最强的语言!

问题在于函数advance(){在foreach范围内。 在您的move()函数中调用该函数,该函数不在同一范围内。

最简单的方法是将移动方法移到您的高级函数下方:

    function advance(){
        clearTimeout(timeout);

        timeout = setTimeout(function(){
            if (currentIndex < ($slides.length - 1) ){
                move(currentIndex + 1);
            } else {
                move(0);
            }
        }, 4000);
    }

    function move(newIndex) {
    //code for move function here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM