0

我在 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>
4

2 回答 2

2

使用 jQuery:

$element.bind('mouseover', function() {
  var id = $(this).attr('id');
});
于 2011-04-14T15:06:55.417 回答
1

为什么要消除元素参数?

在您的场景中,您可以从您的函数中 执行onmouseover="hoverButton(this)"并省去该行。然后将是当时被鼠标悬停的任何元素,您可以通过执行.var button = document.getElementById(element);elementelement.id

但是,由于您在代码中引用了 jQuery,您不妨使用它;)

于 2011-04-14T15:13:46.463 回答