开发者

element id on mouse over

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.

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?


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

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

onmouseover="getid.call(this)"

However, then:

var e = document.getElementById(this);

… is nonsense because this is the element and not the element's 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:

var e = this;


In jQuery:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜