此代码适用于HTML文档中的<script>
标记,但在从外部文件调用时不起作用。
代码:
<html>
<link rel='stylesheet' href='main.css'>
<script src="js/main.js"></script>
<body>
<div class="slideshow-container">
<div class="mySlides fade"> <img src="images/slide1.jpg" style="width:100%"></div>
<div class="mySlides fade"> <img src="images/slide2.jpg" style="width:100%"></div>
<div class="mySlides fade"> <img src="images/slide3.jpg" style="width:100%"></div>
<script>
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex> slides.length) {slideIndex = 1}
slides[slideIndex-1].style = "display:block";
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
</body>
</html>
当我将<script>
标记中的所有内容放入main.js时,会在此行引发错误:slides[slideIndex-1].style = "display:block";
未捕获的TypeError:无法在showSlides设置未定义的属性'style'。
为什么有任何想法? 谢谢!