微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

最近生成的元素的 document.getElementById

如何解决最近生成的元素的 document.getElementById

抱歉,我已阅读有关此主题的先前主题,但在我的情况下它仍然不起作用!

一些上下文是这是一个简单的javascript游戏。当用户将鼠标悬停在库存项目上时,我希望它显示该项目的简短描述。

23/06/2021 编辑 - 好的,这是一个精简版 相关代码

**HTML**
<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta http-equiv="X-UA-Compatible" content="IE=edge">
    <Meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script defer src="scaled.js"></script>
    <link rel="stylesheet" href="scaled.css">


    <title>Scaled</title>
</head>
<body>
    
<div id= "inventory" class = "inventory" ></div>

<div id= "itemtext" class = "itemtext" >A test item!</div>

<button id = "button" onclick = "addImage()">test</button> 

   
</body>
</html>




 **CSS**

.itemtext{
    position: absolute;
    visibility: hidden;
    font-size: 80px;
    top:50px;
    color: red;  
    z-index: 200;
   
}

.itemtext-on{
    position: absolute;
    visibility: initial;
    color: green; 
    font-size: 80px;
    top:50px;
    z-index: 200;
   
}

#button {
    height: 40px;
    width: 40px;
    color: blue;
}

**Javascript**
const itemText = document.getElementById('itemtext');
const inventory = document.getElementById('inventory');


function reveal() {
    itemText.classList.toggle('itemtext-on');
 }

 
 document.getElementById("Div1").onmouSEOver =  function()  {reveal()};
 

function addImage(){ 

var a = document.createElement("div");
 a.id = "Div1"; 
 var iconUrl = document.createElement("img");
 iconUrl.src = "bla.jpg";
 a.appendChild(itemText);
 a.appendChild(iconUrl);
 inventory.appendChild(a);
}

错误信息是: “未捕获的类型错误:无法设置 null 的属性 'onmouSEOver' 在 scaled.js:10"

所以它不喜欢我试图为尚不存在的 div 记录.getElementById 的事实。

感谢任何/所有帮助:)

解决方法

我已经编辑了上面的代码,使其成为一个最小的可重现示例。我开始认为我可以从一开始就让 Div1 存在,但让它完全隐藏。然后当添加库存项目时,它可能会显示出来! :D

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。