鼠标悬停上的图像标记未激发

Image Tag OnMouseOver Not Fired

本文关键字:图像 悬停 鼠标      更新时间:2023-09-26

我有非常简单的代码,我不知道为什么当鼠标在图像上时Foo函数没有启动:

here <img id="sss" alt="some image" onmouseover="Foo(this);" src="https://www.google.com/intl/en_com/images/srpr/logo3w.png" width="16" height="16"   />
<div onmouseover="Foo(this);"> 
    THIS IS DIV
</div>
function Foo(obj) 
{
    alert('s');
}

更新1:

实际情况是,我动态地创建图像元素,然后将其添加到页面中。Foo函数已经在JS文件中,但它从未被调用过。

您当前拥有的代码是正确的,如图所示。我猜你的问题是Foo在你的页面上不是全球性的。


此外,您可以使用callthis作为参数传递给函数,而不是将其设置为函数内部的this值

onmouseover="Foo.call(this);"
function Foo()  {
    alert(this.src); //this is the img you just mouse-overed 
}

最后,考虑将Foo更改为foo,因为在JavaScript中,以大写字母开头的函数通常表示构造函数。

如果这是您的实际代码,那么唯一的问题是您需要将JavaScript封装在<script>:中

<script>
function Foo(obj) {
    alert('s');
}
</script>​

查看演示:

  • http://jsfiddle.net/NmSBs/

EDIT:只要<head> 中包含脚本,代码就没有问题

试试看:jsfiddle