简体   繁体   English

鼠标悬停时的元素 ID

[英]element id on mouse over

I'm using JavaScript to get the element's id on mouse over.我正在使用 JavaScript 在鼠标悬停时获取元素的 ID。 But I am not getting it.但我不明白。 As per my code it is showing null.根据我的代码,它显示 null。

My code is:我的代码是:

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

and I am calling the function on:我打电话给 function:

<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?

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);" />

The value of intrinsic event attributes is the function body .内在事件属性的值是 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() .当您调用没有 object 的 function 时,它与window.thefunction()相同。 So you are calling window.getid() so this (inside the getid function) is the window object.所以你正在调用window.getid()所以this (在 getid 函数内)是 window object。

If you really want to use intrinsic event attributes (hint: don't ), then you have to be explicit about what this is.如果你真的想使用内在事件属性(提示:不要),那么你必须明确this是什么。

onmouseover="getid.call(this)"

However, then:然而,那么:

var e = document.getElementById(this);

… is nonsense because this is 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;

In jQuery:在 jQuery 中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM