简体   繁体   English

为什么我的.js文件似乎对我的.html文件没有任何作用?

[英]Why doesn't my .js file appear to do anything to my .html file?

I'm trying to create a basic image slider that just automatically slides through any given amount of images placed inside a div. 我正在尝试创建一个基本的图像滑块,该滑块将自动在div内放置的任何给定数量的图像之间滑动。

HTML 的HTML

<head>
    <script type="text/javascript" src="slider.js"></script>
</head>

<div class="images">
        <img class="slides" src="img01.jpg">
        <img class="slides" src="img02.jpg">            
        <img class="slides" src="img03.jpg">        
        <img class="slides" src="img04.jpg">    
</div>

JavaScript 的JavaScript

var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("slides");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}
    x[myIndex-1].style.display = "block";
    setTimeout(carousel, 2000); // Change image every 2 seconds
}

But at the moment, it seems that this code isn't doing anything at all, this is the current output of the page. 但目前看来,这段代码根本没有执行任何操作,这是页面的当前输出。 在此处输入图片说明

So as you can see, the images are just being stacked on top of one and another instead of being played as a slideshow. 因此,您可以看到,图像只是堆叠在一起,而不是以幻灯片形式播放。

You're loading your script before the HTML is rendered, so when it tries to getElementsByClassName , there's nothing for it to find. 您需要在呈现HTML之前加载脚本,因此当脚本尝试获取getElementsByClassName ,找不到任何内容。 Try moving to to below your HTML. 尝试移至HTML下方。 And as a in a comment above, you're calling your function carousel() before you define it. 作为上面的评论,您在定义函数carousel()之前就已经对其进行了调用。 Move that line to below the function definition. 将该行移到函数定义下方。

Additionally, you can use 此外,您可以使用

<script>
    document.addEventListener("DOMContentLoaded", function(event) {
        // all of your JavaScript goes here
    });
</script>

This will only load your JavaScript after the HTML is loaded and you can leave it in the head. 这只会在HTML加载后才加载JavaScript,您可以将其放在头部。

Put the carousel(); 放入carousel(); call after the html. 调用html之后。 That way the javascript won't be invoked before the html is loaded. 这样,将不会在加载html之前调用javascript。

There is no call to the carousel method after the images have been loaded. 加载图像后,不会调用旋转木马方法。 You can do the following in your javascript file "slider.js" 您可以在JavaScript文件“ slider.js”中执行以下操作

window.onload = function() { casousel(); };

This would invoke the carousel function on window load. 这将在窗口加载时调用轮播功能。

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

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