Is there a way to grab the current item id on mouse over in javascript?
I have a method in javascript and i'm trying to grab the id of an element on mouse over, is there a way to do this?
So say I have a method which takes no arguments
function noArgs() {}
and I have two paragraphs with the id of p1 and p2, how could I get the id of the hovered paragraph?
EDIT: This is currently how I'm grabbing the id's, which I want to eliminate the "element" argument in the method
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head开发者_运维技巧>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" href="js/jquery.js"></script>
<script type="text/javascript">
function hoverButton(element) {
var button = document.getElementById(element);
switch (button.state) {
case "up":
button.style.backgroundPosition = "top";
button.state = "down";
break;
default:
button.style.backgroundPosition = "bottom";
button.state = "up";
break;
}
}
</script>
<style type="text/css">
.button {
background-image: url("images/button.png");
width: 100px;
height 50px;
background-position: top;
border: none;
font-size: 18px;
}
</style>
</head>
<body>
<input type="submit" id="submit_button" class="button" value="Submit" state="up" onmouseover="hoverButton('submit_button')" onmouseout="hoverButton('submit_button')"/>
<input type="submit" id="submit_button2" class="button" value="Submit" state="up" onmouseover="hoverButton('submit_button2')" onmouseout="hoverButton('submit_button2')"/>
</body>
</html>
using jQuery:
$element.bind('mouseover', function() {
var id = $(this).attr('id');
});
Why do you want to eliminate the element argument?
In your scenario, you could do onmouseover="hoverButton(this)"
and dispense with the var button = document.getElementById(element);
line from your function. element
would then be whichever element was being moused-over at the time, and you could get its ID (should you want it) by doing element.id
.
However, as you've got a reference to jQuery in your code, you might as well use it ;)
精彩评论