Onmouseover 事件在非预期时触发

Onmouseover event is fired when not expected

我正在学习 javascript 并试验鼠标事件。在此代码中,当我在警告框的帮助下将鼠标放在元素上时,我试图操纵该元素。然而,问题是即使鼠标不在元素上,也会显示警告框。

<!DOCTYPE html>
<html>

<head>
    <title>testing</title>
</head>

<body>
    <a>dasdasd</a>
    <p id="k">as</p>

    <script type="text/javascript">
     
     document.getElementById("k").onmouseover=alert('Hello');
     
    </script>
</body>

</html>

尝试在<p>

中添加onmouseover="mouseover()"
       function mouseover() {
            alert('Hello');
         }

<!DOCTYPE html>
<html>

<head>
    <title>testing</title>
</head>

<body>
    <a>dasdasd</a>
    <p id="k" onmouseover="mouseover()">as</p>

    <script type="text/javascript">
     function mouseover() {
     alert('Hello');
     }
    </script>
</body>

</html>

你需要像这样把它放在一个函数中。

<!DOCTYPE html>
<html>

<head>
    <title>testing</title>
</head>

<body>
    <a>dasdasd</a>
    <p id="k">as</p>

    <script type="text/javascript">
     
     document.getElementById("k").onmouseover = function(){alert('Hello')};
     
    </script>
</body>

</html>

试试这个(JQuery):

$(document).ready(function(){
    $("p").mouseover(function(){
        alert("Hello");
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<p>Move the mouse pointer over this paragraph.</p>

</body>
</html>

属性 onmouseover 期望您向它分配一个函数,而不是分配一个表达式的求值,在这种情况下:alert("hello")。因此,当文档加载时,它会评估该表达式并显示警报,然后将 null 值分配给 onmouseover 属性,这就是警报仅显示一次的原因。

为了您的目标,您可以使用匿名函数来包装警报并将其分配给 属性。检查下一个示例:

<!DOCTYPE html>
<html>

<head>
    <title>testing</title>
</head>

<body>
    <a>dasdasd</a>
    <p id="k" style="border: 1px solid red">as</p>

    <script type="text/javascript">
     
     document.getElementById("k").onmouseover = function() {alert('Hello')};
     
    </script>
</body>

</html>

问题是,alert 函数之后的 () 导致在页面加载时调用该函数,您会看到 alert.在匿名函数内部调用该函数,这将确保仅当触发 事件 (onmouseover) 时才会调用该函数:

document.getElementById("k").onmouseover = function(){alert('Hello')};
<a>dasdasd</a>
<p id="k">as</p>