按 javascript 中的索引访问 html 集合时显示未定义

showing undefined when acessing the html collection by index in javascript

Javascript

const box = document.getElementsByClassName('preview');
console.log(box[1])

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Photo Gallery</title>
    <link rel="stylesheet" href="css/gallery.css">
    <script src="js/gallery.js"></script>
</head>

<body>

    <div id="image">
        Hover over an image below to display here.
    </div>

    <img class="preview" alt="Styling with a Bandana" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover="upDate(this)" onmouseout="unDo()">

    <img class="preview" alt="With My Boy" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover="upDate(this)" onmouseout="unDo()">

    <img class="preview" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt="Young Puppy" onmouseover="upDate(this)" onmouseout="unDo()">

</body></html>

我只想获取我的框1 或任何其他索引的值,但它显示未定义。

您正试图在页面完成加载 DOM 之前访问 HTML 元素。尝试将 <script src="js/gallery.js"></script> 元素移动到 </body> 结束标记之前。

这里发生的事情是您在页面的头部添加了 js 脚本。每当页面加载时,脚本首先执行,它无法找到 class 元素和 returning 未定义。您可以通过两种简单的方法解决此问题。

  1. 将您的脚本从头部移到 body 标记的末尾。如果您出于某种原因不想移动脚本,请执行第二步。
  2. 在此
  3. 中添加您的 JS 代码

window.addEventListener('DOMContentLoaded', (event) => { console.log('DOM fully loaded and parsed'); });

当您在此函数中添加 JS 代码时,仅当 DOM 已加载时才执行您的代码意味着在 HTML 元素加载之后。

检查我演示场景的片段。删除上面的函数,只添加你的 js 代码,看看它会再次 return undefined。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Photo Gallery</title>
    <link rel="stylesheet" href="css/gallery.css">
    <script src="js/gallery.js"></script>
    <script>
    window.addEventListener('DOMContentLoaded', (event) => {
    const box = document.getElementsByClassName('preview');
console.log(box[1])
    
    });
   
    </script>
</head>

<body>

    <div id="image">
        Hover over an image below to display here.
    </div>

    <img class="preview" alt="Styling with a Bandana" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover="upDate(this)" onmouseout="unDo()"/>

    <img class="preview" alt="With My Boy" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover="upDate(this)" onmouseout="unDo()"/>

    <img class="preview" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt="Young Puppy" onmouseover="upDate(this)" onmouseout="unDo()"/>

</body></html>