获取我使用 jQuery 悬停的元素的 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1777210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get ID of the element I hover over with jQuery?
提问by Andrew
I have a bunch of elements that look like this:
我有一堆看起来像这样的元素:
<span class='tags' id='html'>html</span>
<span class='tags' id='php'>php</span>
<span class='tags' id='sql'>sql</span>
How would I get the name of the id of the one I hover over, so I could output something like "You're hovering over the htmltag". (What I want to do isn't that arbitrary, but I do need to get the name of the tag the user hovers over in order to do it.)
我如何获得我悬停的那个 ID 的名称,以便我可以输出类似“你悬停在html标签上”的内容。(我想做的并不是那么随意,但我确实需要获取用户悬停在其上的标签名称才能做到这一点。)
回答by Andy Gaskell
回答by rfunduk
$('.tags').hover(
function() { console.log( 'hovering on' , $(this).attr('id') ); },
function() {}
);
Second empty function is for mouse out, you'll probably want to do something on that event as well.
第二个空函数用于鼠标移出,您可能还想在该事件上做一些事情。
回答by Harveer Singh Aulakh
Use this one:-
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").hover(function(){
//if get onhover id
alert("NOW GET ON HOVER ID NAME:--"+" "+this.id);
//if get onhover class
alert("NOW GET ON HOVER CLASS NAME:--"+" "+$(this).attr('class'));
});
});
</script>
</head>
<body>
<p class="getclass" id="get_class_id" >Hover the mouse</p>
</body>
</html>
回答by Vishal
These solutions still returned an empty alert for me. For me, following worked when I handled the event object passed to the hover function:
这些解决方案仍然为我返回了一个空警报。对我来说,当我处理传递给悬停函数的事件对象时,以下工作:
$(".input-box").hover(function(eventObj) {
alert(eventObj.target.id);
});