问题描述
|
我正在使用JavaScript在鼠标悬停时获取元素的ID。但是我不明白。
根据我的代码,它显示为空。
我的代码是:
function getid() {
var e = document.getElementById(this);
alert(e);
}
我在调用该函数:
<input
style=\"margin: 8px 4px 4px 4px; width:142px; height:117px;\"
type=\"image\"
id=\"img\"
src=\"images2.jpg\"
onmouSEOver=\"getid();\"
onmouSEOut=\"outmouse();\"
/>
如何在鼠标悬停时获取元素ID?
解决方法
检查这个
<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);\"
/>
, 内在事件属性的值是函数主体。您所拥有的与:
onmouseover = function () {
getid();
}
调用不带对象的函数时,与window.thefunction()
相同。因此,您正在调用window.getid()
,因此this
(在getid函数内部)是窗口对象。
如果您真的想使用内部事件属性(提示:不要),则必须明确表示ѭ6是什么。
onmouseover=\"getid.call(this)\"
但是,然后:
var e = document.getElementById(this);
…是无意义的,因为this
是元素而不是元素的ID。
您可以从this
获得id属性,并使用它来查找元素,但这很愚蠢,因为您可以简单地进行以下操作:
var e = this;
, 在jQuery中:
$(input).mouseover(function()
{
var showID = $(this).attr(\"ID\");
alert(showID);
});