我正在w3school中从事轮播工作。他们实际上有一个内联javascript代码,我正在尝试将其转换为外部javascript文件。我的外部文件中有此代码
window.addEventListener('DOMContentLoaded', function () {
var slideIndex = 1;
showSlides(slideIndex);
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
}, false);
但是当我浏览轮播时,它会显示错误Uncaught ReferenceError: currentSlide is not defined at HTMLSpanElement.onclick
,并且无法正常工作/导航轮播中的图像
这是HTML代码
<div class="slideshow">
<div class="slideshow-container">
<div class="mySlides fade">
<img class="carousel-item" src="https://lorempixel.com/800/400/food/1">
</div>
<div class="mySlides fade">
<img class="carousel-item" src="https://lorempixel.com/800/400/food/2">
</div>
</div>
<div class="slide-nav">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
</div>
</div>
<script type="text/javascript" src="js/components.js"></script>
答案 0 :(得分:1)
因为currentSlide
无法全局访问(HTML内联事件处理程序在全局范围内运行)。您需要在全局范围内对其进行定义才能使其起作用:
function currentSlide(n) {
showSlides(slideIndex = n);
}
window.addEventListener("DOMContentLoaded", function() {...}, false);