开发者

Get ID of the element I hover over with jQuery?

I have 开发者_Python百科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 html tag". (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.)


mouseover should do the trick.

$('.tags').mouseover(function() {
   alert(this.id);
});

Note that if you want to know when the mouse leaves as well, you can use hover.


$('.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.


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);  
});

Source of this solution


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜