简体   繁体   English

浏览器 console.log 和代码 console.log 显示不同

[英]Browser console.log and code console.log showing different

I was creating a carousel.我正在创建一个轮播。 I don't know what the hell is going on anymore, in my HTML:我不知道到底发生了什么,在我的 HTML 中:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="Carousel.css">
    <script src="Carousel.js"></script>
    <title>Carousel</title>
</head>

<body>
    <h1>This is the Carousel</h1>

    <div id="carousel">
        <div class="carousel_item carousel_item--visible"><img src="Images/Sasuke.jpg" alt="" srcset=""></div>
        <div class="carousel_item"><img src="Images/Spider-man.jpg"></div>
        <div class="carousel_item"><img src="Images/The Dark Knight.jpg" ></div>
        <div class="carousel_item"><img src="Images/Arcane.jpg"></div>

        <div class="carousel_actions">
            <button id="carousel_button--prev"> < </button>
            <button id="carousel_button--next"> > </button>
        </div>
    </div>


</body>

</html>

and my JS:和我的 JS:

let curr_pos = 0;
const slide = document.getElementsByClassName('carousel_item');
console.log(slide.length);

In this as you can see I have 4 items with.carousel_item so the console should display 4, however it is showing 0 .But if I use console.log(slide.length) in Browser console then it shows 4 .在这个你可以看到我有 4 个项目 with.carousel_item 所以控制台应该显示 4 ,但是它显示0 。但是如果我在浏览器控制台中使用 console.log(slide.length) 那么它显示4

Now either I have to start Js from scratch or the browser is gone mental.现在要么我必须从头开始 Js,要么浏览器已经疯了。 Please someone help!请有人帮忙!

HTML documents are parsed top to bottom. HTML 文档从上到下解析。 When a script tag is encountered, all other parsing stops until the script has finished execution.当遇到script标签时,所有其他解析都会停止,直到脚本完成执行。

Therefore, elements placed after the script tag will not be visible in the DOM to the script.因此,放置在script标签之后的元素在 DOM 中对脚本来说是不可见的。

To solve this, move the script tag's position to the bottom of the body tag:为了解决这个问题,将script标签的 position 移动到body标签的底部:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="Carousel.css">
    <title>Carousel</title>
</head>

<body>
    <h1>This is the Carousel</h1>

    <div id="carousel">
        <div class="carousel_item carousel_item--visible"><img src="Images/Sasuke.jpg" alt="" srcset=""></div>
        <div class="carousel_item"><img src="Images/Spider-man.jpg"></div>
        <div class="carousel_item"><img src="Images/The Dark Knight.jpg" ></div>
        <div class="carousel_item"><img src="Images/Arcane.jpg"></div>

        <div class="carousel_actions">
            <button id="carousel_button--prev"> < </button>
            <button id="carousel_button--next"> > </button>
        </div>
    </div>

    <script src="Carousel.js"></script>
</body>

</html>

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

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