Javascript 鼠标悬停时的元素 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6186065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:37:55  来源:igfitidea点击:

element id on mouse over

javascripthtml

提问by kawade

I'm using JavaScript to get the element's id on mouse over. But I am not getting it. As per my code it is showing null.

我正在使用 JavaScript 在鼠标悬停时获取元素的 id。但我不明白。根据我的代码,它显示为空。

My code is:

我的代码是:

function getid() {
  var e = document.getElementById(this);
  alert(e);
}

and I am calling the function on:

我正在调用该函数:

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

How can I get the elements id on mouse over?

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

回答by Anand Thangappan

check this

检查这个

function getid(obj) {
  alert(obj.id);
}
<input style="margin: 8px 4px 4px; width:142px; height:117px;" type="image" id="img" src="images2.jpg" onmouseover="getid(this);" />

回答by Quentin

The value of intrinsic event attributes is the function body. What you have is the same as:

内在事件属性的值是函数。你拥有的是相同的:

onmouseover = function () {
    getid();
}

When you call a function without an object, it is the same as window.thefunction(). So you are calling window.getid()so this(inside the getid function) is the window object.

当你调用一个没有对象的函数时,它与window.thefunction(). 所以你调用window.getid()so this(在 getid 函数内)是 window 对象。

If you really want to use intrinsic event attributes (hint: don't), then you have to be explicit about what thisis.

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

onmouseover="getid.call(this)"

However, then:

然而,那么:

var e = document.getElementById(this);

… is nonsense because thisis the element and not the element's id.

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

You could get the id property from this, and use that to look up the element, but that would be silly as you can simply:

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

var e = this;

回答by Damien

In jQuery:

在 jQuery 中:

$(input).mouseover(function()
{
   var showID = $(this).attr("ID");
   alert(showID);
});