有没有办法在javascript中抓取鼠标上的当前项ID?

时间:2011-04-14 15:02:54

标签: javascript jquery html onmouseover

我在javascript中有一个方法,我试图在鼠标上抓取一个元素的id,有没有办法做到这一点?

所以说我有一个不带参数的方法

function noArgs() {}

我有两个id为p1和p2的段落,我怎么能得到悬停段落的id?

编辑:这是目前我抓取id的方法,我想删除方法中的“元素”参数

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

2 个答案:

答案 0 :(得分:2)

使用jQuery:

$element.bind('mouseover', function() {
  var id = $(this).attr('id');
});

答案 1 :(得分:1)

为什么要删除元素参数?

在您的方案中,您可以执行onmouseover="hoverButton(this)"并免除功能中的var button = document.getElementById(element);行。 element然后就会被当时被篡改的元素所占据,你可以通过element.id得到它的ID(如果你想要的话)。

但是,正如您在代码中引用jQuery一样,您也可以使用它;)