简体   繁体   English

控制台中的Javascript滑块错误且不滑动

[英]Javascript slider errors in console and not sliding

The page works fine, but the slider doesn't slide to the next image. 该页面工作正常,但滑块不会滑动到下一张图像。 JSFiddle makes it work out fine and the images slide, yet on localhost or any live website it fails. JSFiddle使它工作正常并且图像可以滑动,但是在localhost或任何实时网站上,它均失败。

<script>

    var slides = document.querySelectorAll('#slides.klant');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);

function nextSlide(){
    slides[currentSlide].className = 'klant';
    currentSlide = (currentSlide+1)%slides.length;
    slides[currentSlide].className = 'klant showing';
}


</script>

<title>Untitled Document</title>
</head>

<body>

<div id="ads">
<ul id="slides">
    <li class="klant showing"><img src="img/first.jpg"></li>
    <li class="klant"><img src="img/second.jpg"></li>
    <li class="klant"><img src="img/third.jpg"></li>
    <li class="klant"><img src="img/fourth.jpg"></li>
    <li class="klant"><img src="img/fifth.jpg"></li>
</ul>
</div>

I get an error "Uncaught TypeError: Cannot set property 'className' of undefined" on the slides[currentSlide].className = 'klant'; 我在slides[currentSlide].className = 'klant';上遇到错误“未捕获的TypeError:无法设置未定义的属性'className'” slides[currentSlide].className = 'klant'; part of the function but can't figure out what's going wrong. 函数的一部分,但无法找出问题所在。

the script executes before the page finished loading, so the querySelectorAll returns an empty array. 该脚本在页面加载完成之前执行,因此querySelectorAll返回一个空数组。 copy your script to the end of the <body> and it will work fine. 将您的脚本复制到<body>的末尾,它将可以正常工作。

On JsFiddle it works because by default script executes there after load. 在JsFiddle上它有效,因为默认情况下脚本在加载后在此执行。

With input from Teemu(see comments below), the major issue is that your script is loaded before the HTML. 使用Teemu的输入(请参阅下面的注释),主要问题是您的脚本在HTML之前加载。 Thus, the elements are undefined at the point the script ran. 因此,在脚本运行时未定义元素。 Wrapping the script in an onload event should solve the problem and putting a space between #slides and .klant in your script. onload事件中包装脚本应该可以解决问题,并在脚本中的#slides.klant之间放置一个空格。 See below example: 请参见以下示例:

<script>

window.onload = function () {
   var slides = document.querySelectorAll('#slides .klant');
   var currentSlide = 0;
   var slideInterval = setInterval(nextSlide,2000);


function nextSlide(){
        slides[currentSlide].className = 'klant';
        currentSlide = (currentSlide+1)%slides.length;
        slides[currentSlide].className = 'klant showing';
    }

 }

</script>
Just Replace
 line var slides = document.querySelectorAll('#slides.klant');

with

    var sliderparent = document.getElementById('slides');
var slides = sliderparent.querySelectorAll('.klant');

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

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