javascript - 无法触发 onmouseenter 事件?

标签 javascript

当我直接在 html 中包含对该函数的引用时,我能够使 onmousesenter 正常工作,但读到它是错误的形式并且想改进我的代码 - 但现在我无法让它运行,尽管我显示它的代码确实触发了该功能,我只是不确定为什么它的其余部分现在无法运行:

<DOCTYPE! html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<title>Sexism in Silicon Valley</title>
<script src="index.js"></script>
</head>
<body id="body1">
<div class="parent">
    <img src="kstartup.png" class="logos" id="id1"></img>
    <img src="uber.png" class="logos" id="id2"></img>
    <img src="kpcb.png" class="logos" id="id3"></img>
    <img id="id4" src="r1startup.png" class="logos"></img>
</div>

Javascript(index.js):

function mouseenter() { 
    alert("hey");
    var z = document.getElementsByClassName("parent");
    for (var i = 0; i < z.length; i++) {
        z[i].style.background = "black";
    } 
    var bod = document.getElementById("body1");
    bod.style.background = "black";

} 
document.getElementById("id1").onmouseenter = mouseenter();

警报在我加载页面后立即消失,而不是在我的鼠标进入 id1 时消失。为什么我的鼠标输入id不触发?

最佳答案

当您尝试访问 ID id1 时,您的文档 DOM 尚未准备好元素。

document.getElementById("id1").onmouseenter = mouseenter; // Don't execute()
// Since this code is inside HEAD, JS does not know about any #id1 Element yet.

因为您正在调用 <script>标签内 <head>而不是收盘前的底部</body>标签。

<script src="index.js"></script> <!-- Makes sure parser readed all the elements -->
</body>
</html>

关于javascript - 无法触发 onmouseenter 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33202079/

相关文章:

javascript - 如何在 vue 3 中实现可重用的组件输入?

javascript - 什么时候可以调用对象原型(prototype)链上的方法?

javascript - onclick 时更改 div 元素的可见性和不透明度

javascript - onClick 触发所有元素。我只想触发指定的元素

javascript - "if (!' '.replace(/^/, String))"是做什么的?

javascript - 根据规范,js 中最大的 BigInt 值是多少

javascript - 打印不适合纸张的主页的内容页

javascript - 如何跨多个浏览器窗口从现有页面拆分 DOM?

javascript - 同一页面上有两个不同的 google API

javascript - 将 QtQuick/QML 对象传递给 javascript 函数后访问其属性