2009-11-21 11 views
15

Ho un sacco di elementi che assomigliano a questo:Ottieni l'ID dell'elemento al passaggio del mouse con jQuery?

<span class='tags' id='html'>html</span> 
<span class='tags' id='php'>php</span> 
<span class='tags' id='sql'>sql</span> 

Come dovrei ottenere il nome del id di quella che ho con il mouse sopra, così ho potuto uscita qualcosa del tipo "Stai in bilico sopra la tag HTML ". (Quello che voglio fare non è che arbitraria, ma ho bisogno di ottenere il nome del tag che l'utente passa sopra al fine di farlo.)

risposta

31

mouseover dovrebbe fare il trucco.

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

Si noti che se si vuole sapere quando il mouse lascia così, è possibile utilizzare hover.

+0

che visualizza una finestra di avviso vuota. = /. – Andrew

+0

Ho lavorato per me a jsbin - http://jsbin.com/ohili –

+0

Oops, ho avuto due classi denominate "tag" in caso di incidente; Ne ho fatto uno per una lista e uno per formattare il tag. hehe. Grazie! – Andrew

9
$('.tags').hover(
    function() { console.log('hovering on' , $(this).attr('id')); }, 
    function() {} 
); 

seconda funzione è vuota per il mouse fuori, Probabilmente vorrà fare qualcosa anche in quell'evento.

0

Queste soluzioni hanno restituito ancora un avviso vuoto per me. Per me, in seguito ha lavorato quando ho gestito l'oggetto evento passato alla funzione hover:

$(".input-box").hover(function(eventObj) { 
    alert(eventObj.target.id); 
}); 

Source of this solution

0

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>

Problemi correlati