如何解决有没有办法在JavaScript上的鼠标悬停时获取当前商品的ID?
| 我在javascript中有一个方法,而我试图将鼠标悬停在某个元素的ID上,有没有办法做到这一点? 所以说我有一个不带参数的方法function noArgs() {}
并且我有两个段落的ID为p1和p2,我如何获取悬停的段落的ID?
编辑:这是我目前正在获取id的方式,我想消除方法中的\“ element \”参数
<!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>
解决方法
使用jQuery:
$element.bind(\'mouseover\',function() {
var id = $(this).attr(\'id\');
});
,为什么要消除element参数?
在您的方案中,您可以做onmouseover=\"hoverButton(this)\"
,而不必使用函数中的var button = document.getElementById(element);
行。 element
将是当时被鼠标悬停的元素,您可以通过doing6ѭ来获取它的ID(是否需要)。
但是,由于您在代码中引用了jQuery,因此不妨使用它;)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。