鼠标悬停的元素ID

kaw*_*ade 9 html javascript

我正在使用JavaScript来获取鼠标悬停时元素的id.但我没有得到它.根据我的代码,它显示为null.

我的代码是:

function getid() {
  var e = document.getElementById(this);
  alert(e);
}
Run Code Online (Sandbox Code Playgroud)

我正在调用函数:

<input 
  style="margin: 8px 4px 4px 4px; width:142px; height:117px;"
  type="image" 
  id="img" 
  src="images2.jpg" 
  onmouseover="getid();" 
  onmouseout="outmouse();" 
/> 
Run Code Online (Sandbox Code Playgroud)

如何在鼠标悬停时获取元素id?

Ana*_*pan 14

检查一下

<script>
  function getid(obj) {
    alert(obj.id);
  }
</script>


<input 
  style="margin: 8px 4px 4px; width:142px; height:117px;" 
  type="image" 
  id="img" 
  src="images2.jpg" 
  onmouseover="getid(this);" 
  onmouseout="outmouse(this);" 
/> 
Run Code Online (Sandbox Code Playgroud)


Que*_*tin 7

内部事件属性的值是函数.你有什么是相同的:

onmouseover = function () {
    getid();
}
Run Code Online (Sandbox Code Playgroud)

当你调用一个没有对象的函数时,它就像是一样window.thefunction().所以,你在呼唤window.getid()这样this(的的getId函数内)是窗口对象.

如果你真的想使用内部事件属性(提示:不要),那么你必须明确是什么this.

onmouseover="getid.call(this)"
Run Code Online (Sandbox Code Playgroud)

但是,那么:

var e = document.getElementById(this);
Run Code Online (Sandbox Code Playgroud)

...是无稽之谈,因为this它是元素而不是元素的id.

你可以从中获取id属性this,并使用它来查找元素,但这很简单,因为你可以简单地:

var e = this;
Run Code Online (Sandbox Code Playgroud)