我正在学习 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>
最佳答案
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>
关于javascript - Onmouseover 事件在非预期时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53644539/