gpt4 book ai didi

javascript - 函数上未捕获的 referenceError

转载 作者:行者123 更新时间:2023-11-30 16:18:19 27 4
gpt4 key购买 nike

我正在关注一个简​​单的 tut,它有望构建一个响应式 slider ,但是它一直告诉我控制台中有一个错误指向一个名为 advance()

的函数

这是 slider 的简单 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() 函数中调用。

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

    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

关于javascript - 函数上未捕获的 referenceError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35138565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com