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

问题描述 投票:0回答:2

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>

我只想获取我的box 1或任何其他索引的值,但它显示undefined。

javascript html dom getelementsbyclassname
2个回答
0
投票

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


0
投票

这里发生的事情是您在页面的顶部添加了js脚本。每当页面加载时,脚本都会首先执行,并且它无法找到class元素并返回undefined。您可以通过两种简单的方法解决此问题。

  1. 从头开始移动脚本,并将其添加到body标签的末尾。如果您由于某种原因不想移动脚本,请执行第二步。
  2. 在此添加您的JS代码

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

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

查看我已演示该场景的代码段。删除上面的函数,然后仅添加您的js代码,以查看它是否再次返回未定义。

<!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>
© www.soinside.com 2019 - 2024. All rights reserved.